### Setup Resource Module Builder Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/network/dev_guide/developing_resource_modules_network.rst Commands to clone the resource module builder repository and install its required dependencies. ```bash git clone https://github.com/ansible-network/resource_module_builder.git pip install -r requirements.txt ``` -------------------------------- ### Define setup tasks for integration tests Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/community/collection_contributors/collection_integration_add.rst Install and start the required service using Ansible tasks in the setup target's main.yml file. ```yaml - name: Install abstract service package: name: abstract_service - name: Run the service systemd: name: abstract_service state: started ``` -------------------------------- ### Setup PostgreSQL Database Tasks Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/community/collection_contributors/collection_integration_add.rst Ansible tasks to install PostgreSQL packages, initialize the database cluster, and start the service. ```yaml - name: Install required packages package: name: - apt-utils - postgresql - postgresql-common - python3-psycopg2 - name: Initialize PostgreSQL shell: . /usr/share/postgresql-common/maintscripts-functions && set_system_locale && /usr/bin/pg_createcluster -u postgres 12 main args: creates: /etc/postgresql/12/ - name: Start PostgreSQL service ansible.builtin.service: name: postgresql state: started ``` -------------------------------- ### Ansible Ad Hoc Command Examples (Shell) Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/tips_tricks/sample_setup.rst These examples demonstrate Ansible's ad hoc command capabilities for quick tasks. They show how to ping hosts and execute commands remotely, useful for immediate actions or checks. ```shell ansible boston -i production -m ping ``` ```shell ansible boston -i production -m command -a '/sbin/reboot' ``` -------------------------------- ### Ansible Command-Line Execution Examples (Shell) Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/tips_tricks/sample_setup.rst These commands illustrate how to execute Ansible playbooks with specific targets and limits. They show how to run the entire site, specific playbooks, or limit execution to certain hosts or groups. ```shell ansible-playbook site.yml --limit webservers ``` ```shell ansible-playbook webservers.yml ``` ```shell ansible-playbook -i production site.yml ``` ```shell ansible-playbook -i production site.yml --tags ntp ``` ```shell ansible-playbook -i production webservers.yml ``` ```shell ansible-playbook -i production webservers.yml --limit boston ``` ```shell ansible-playbook -i production webservers.yml --limit boston[0:9] ``` ```shell ansible-playbook -i production webservers.yml --limit boston[10:19] ``` -------------------------------- ### Initialize Ansible Project Directory Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/getting_started/get_started_ansible.rst Creates a dedicated directory for Ansible automation files and navigates into it. This structure is recommended for better source control management and content reusability. ```bash mkdir ansible_quickstart && cd ansible_quickstart ``` -------------------------------- ### Complete Action Plugin Example (Python) Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/dev_guide/developing_plugins.rst A comprehensive example of an Ansible action plugin that executes the 'setup' module, retrieves the remote date, and calculates the time difference between the control node and the target machine. It includes necessary imports and class structure. ```python #!/usr/bin/python # Make coding more python3-ish, this is required for contributions to Ansible from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.action import ActionBase from datetime import datetime class ActionModule(ActionBase): def run(self, tmp=None, task_vars=None): super(ActionModule, self).run(tmp, task_vars) module_args = self._task.args.copy() module_return = self._execute_module(module_name='setup', module_args=module_args, task_vars=task_vars, tmp=tmp) ret = dict() remote_date = None if not module_return.get('failed'): for key, value in module_return['ansible_facts'].items(): if key == 'ansible_date_time': remote_date = value['iso8601'] if remote_date: remote_date_obj = datetime.strptime(remote_date, '%Y-%m-%dT%H:%M:%SZ') time_delta = datetime.utcnow() - remote_date_obj ``` -------------------------------- ### Ansible Dry Run Command Examples (Shell) Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/tips_tricks/sample_setup.rst These commands show how to perform dry runs in Ansible to preview actions without making changes. They are useful for verifying which tasks would run or which hosts would be affected by a command. ```shell ansible-playbook -i production webservers.yml --tags ntp --list-tasks ``` ```shell ansible-playbook -i production webservers.yml --limit boston --list-hosts ``` -------------------------------- ### Install and Uninstall Software on Windows Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/os_guide/windows_usage.rst Demonstrates installing and uninstalling 7-Zip using `win_chocolatey` for package management, `win_package` for MSI files, and `win_command` for manual execution of installers. ```yaml+jinja # Install/uninstall with chocolatey - name: Ensure 7-Zip is installed through Chocolatey win_chocolatey: name: 7zip state: present - name: Ensure 7-Zip is not installed through Chocolatey win_chocolatey: name: 7zip state: absent # Install/uninstall with win_package - name: Download the 7-Zip package win_get_url: url: https://www.7-zip.org/a/7z1701-x64.msi dest: C:\temp\7z.msi - name: Ensure 7-Zip is installed through win_package win_package: path: C:\temp\7z.msi state: present - name: Ensure 7-Zip is not installed through win_package win_package: path: C:\temp\7z.msi state: absent # Install/uninstall with win_command - name: Download the 7-Zip package win_get_url: url: https://www.7-zip.org/a/7z1701-x64.msi dest: C:\temp\7z.msi - name: Check if 7-Zip is already installed win_reg_stat: name: HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{23170F69-40C1-2702-1701-000001000000} register: 7zip_installed - name: Ensure 7-Zip is installed through win_command win_command: C:\Windows\System32\msiexec.exe /i C:\temp\7z.msi /qn /norestart when: 7zip_installed.exists == false - name: Ensure 7-Zip is uninstalled through win_command win_command: C:\Windows\System32\msiexec.exe /x {23170F69-40C1-2702-1701-000001000000} /qn /norestart when: 7zip_installed.exists == true ``` -------------------------------- ### Install Ansible on Ubuntu via PPA Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/installation_guide/installation_distros.rst Configure the Ansible PPA and install the latest Ansible version on Ubuntu. This involves updating package lists, installing prerequisites, adding the PPA, and then installing the ansible package. ```bash $ sudo apt update $ sudo apt install software-properties-common $ sudo add-apt-repository --yes --update ppa:ansible/ansible $ sudo apt install ansible ``` -------------------------------- ### Create Setup Target Directories Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/community/collection_contributors/collection_integration_add.rst Create the necessary directory structure for the setup target. ```bash mkdir -p tests/integration/targets/setup_postgresql_db/tasks ``` -------------------------------- ### Initialize Environment and Get Help Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/dev_guide/testing_integration.rst Source the env-setup script to add bin/ to your PATH, then run ansible-test with the --help flag. Alternatively, call ansible-test directly using its full path. ```shell-session source hacking/env-setup ansible-test --help ``` ```shell-session bin/ansible-test --help ``` -------------------------------- ### Install Ansible via pip Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/getting_started/get_started_ansible.rst Installs the Ansible automation engine using the Python package manager. This command requires a Python environment and pip installed on the host system. ```bash pip install ansible ``` -------------------------------- ### Get relative path from a start point Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/playbook_guide/playbooks_filters.rst Calculates the relative path from a specified starting point to the given path using the `relpath` filter. ```Jinja {{ path | relpath('/etc') }} ``` -------------------------------- ### Unit Test Module Setup with Mocks Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/dev_guide/testing_units_modules.rst Shows how to test module initialization and parameter validation by mocking the command execution and asserting expected failures. ```python def test_rds_module_setup_fails_if_db_instance_identifier_parameter_missing(): # db_instance_identifier parameter is missing set_module_args({ 'state': 'absent', 'apply_immediately': 'True', }) with self.assertRaises(AnsibleFailJson) as result: my_module.setup_json ``` -------------------------------- ### Install Ansible Galaxy Roles using CLI Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/galaxy/user_guide.rst Provides the command to install a role from Ansible Galaxy using the `ansible-galaxy role install` command. It specifies the role by its namespace and name. ```bash $ ansible-galaxy role install namespace.role_name ``` -------------------------------- ### Example Playbook Directory Structure Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/playbook_guide/playbooks_reuse_roles.rst Illustrates a basic directory structure for playbooks, showing how `site.yml`, `webservers.yml`, and `fooservers.yml` might be organized at the top level. ```text # playbooks site.yml webservers.yml fooservers.yml ``` -------------------------------- ### Install nox automation tool Source: https://github.com/ansible/ansible-documentation/blob/devel/README.md Installs the nox automation tool using pip, which is required to run the project's test and build sessions. ```bash python3 -m pip install nox ``` -------------------------------- ### Create integration test directory structure Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/community/collection_contributors/collection_integration_add.rst Use mkdir to establish the necessary directory hierarchy for a setup target. ```bash mkdir -p tests/integration/targets/setup_abstract_service/tasks ``` -------------------------------- ### List Installed Ansible Roles (Bash) Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/galaxy/user_guide.rst Displays the name and version of all roles currently installed in the Ansible roles path. This command helps in inventorying available roles. ```bash $ ansible-galaxy role list - namespace-1.foo, v2.7.2 - namespace2.bar, v2.6.2 ``` -------------------------------- ### Create a Windows Server VM with Vagrant Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/dev_guide/developing_modules_general_windows.rst Initializes and starts a Windows Server 2016 VM using Vagrant, downloading the box and configuring WinRM listeners automatically. ```shell vagrant init jborean93/WindowsServer2016 vagrant up ``` -------------------------------- ### Install Ansible Role to Specific Path Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/galaxy/user_guide.rst Installs an Ansible role into a specified directory using the `--roles-path` option with `ansible-galaxy`. This allows for localized role management. ```bash $ ansible-galaxy role install --roles-path . geerlingguy.apache ``` -------------------------------- ### Resource starting configuration Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/network/user_guide/network_resource_modules.rst Initial state of the loopback100 interface configuration. ```text interface loopback100 ip address 10.10.1.100 255.255.255.0 ipv6 address FC00:100/64 ``` -------------------------------- ### Define a class-based unit test Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/dev_guide/testing_units.rst Example of a class-based test using the unittest framework for organized setup and teardown. ```python import unittest class AddTester(unittest.TestCase): def SetUp(): self.a = 10 self.b = 23 # this function will def test_add(): c = 33 assert self.a + self.b == c # this function will def test_subtract(): c = -13 assert self.a - self.b == c ``` -------------------------------- ### Windows Path Formatting Examples in YAML Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/os_guide/windows_usage.rst Illustrates different ways to define Windows paths in YAML, highlighting good, working, and sometimes problematic approaches regarding backslash escaping. ```ini # GOOD tempdir: C:\Windows\Temp # WORKS tempdir: 'C:\Windows\Temp' tempdir: "C:\\Windows\\Temp" # BAD, BUT SOMETIMES WORKS tempdir: C:\\Windows\\Temp ``` -------------------------------- ### Install Specific Version of Ansible Role Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/galaxy/user_guide.rst Installs a specific version of an Ansible role by appending a comma and the version tag (e.g., Git tag) to the role name. This ensures reproducible deployments. ```bash $ ansible-galaxy role install geerlingguy.apache,3.2.0 ``` -------------------------------- ### Example docs/docsite/extra-docs.yml Structure Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/dev_guide/developing_collections_structure.rst Defines the structure for extra documentation within a collection, including titles andtoctree entries for guides. ```yaml --- sections: - title: Scenario Guide toctree: - scenario_guide ``` -------------------------------- ### List Ansible Facts for a Host Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/reference_appendices/faq.rst Run the `setup` module as an ad hoc action to display all gathered facts (`ansible_` variables) about a specific managed machine. ```shell-session ansible -m setup hostname ``` -------------------------------- ### Install Multiple Ansible Roles from requirements.yml Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/galaxy/user_guide.rst Installs multiple Ansible roles defined in a YAML file named `requirements.yml`. This file specifies roles by source, SCM, version, and optionally a custom name. ```bash $ ansible-galaxy install -r requirements.yml ``` -------------------------------- ### Install Ansible Role from Git Commit Hash Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/galaxy/user_guide.rst Installs a specific Ansible role directly from a Git repository using a commit hash as the version identifier. This is useful for pinning to exact code states. ```bash $ ansible-galaxy role install git+https://github.com/geerlingguy/ansible-role-apache.git,0b7cd353c0250e87a26e0499e59e7fd265cc2f25 ``` -------------------------------- ### Example execution order for roles with duplicate dependencies Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/playbook_guide/playbooks_reuse_roles.rst This text output demonstrates the sequential execution order of roles and their dependencies when `allow_duplicates: true` is used and parameters vary, showing how sub-roles are run for each instance of the parent role. ```text tire(n=1) brake(n=1) wheel(n=1) tire(n=2) brake(n=2) wheel(n=2) ... car ``` -------------------------------- ### Define Roles and Collections in requirements.yml Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/galaxy/user_guide.rst A YAML configuration for installing specific versions of Ansible roles and collections from Galaxy. ```yaml --- roles: # Install a role from Ansible Galaxy. - name: geerlingguy.java version: "1.9.6" collections: # Install a collection from Ansible Galaxy. - name: community.general version: ">=7.0.0" source: https://galaxy.ansible.com ``` -------------------------------- ### Setup ansible-core Environment Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/dev_guide/testing_running_locally.rst Adds ansible-core programs to the system PATH. ```shell source hacking/env-setup ``` -------------------------------- ### Install Ansible Navigator and Builder Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/getting_started_ee/setup_environment.rst Installs the tools required to run and build Execution Environments. Users can install the full navigator suite or just the builder package if testing is not required. ```bash pip3 install ansible-navigator pip3 install ansible-builder ``` -------------------------------- ### Using async_status module with Jinja2 conditionals in Ansible Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/porting_guides/porting_guide_core_2.19.rst The 'started' and 'finished' integer properties of the async_status module can no longer be used directly as boolean values in conditionals. Instead, use the 'started' and 'finished' test plugins for proper boolean evaluation. ```yaml+jinja - async_status: jid: '{{ registered_task_result.ansible_job_id }}' register: job_result until: job_result is finished retries: 5 delay: 10 ``` -------------------------------- ### Split Requirements into Multiple Files Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/galaxy/user_guide.rst Demonstrates how to modularize requirements by including secondary files within a primary requirements.yml file and installing them via the CLI. ```bash # webserver.yml content - src: https://github.com/bennojoy/nginx - src: git+https://bitbucket.org/willthames/git-ansible-galaxy version: v1.4 # requirements.yml content - name: yatesr.timezone - include: /webserver.yml # Command to install $ ansible-galaxy role install -r requirements.yml ``` -------------------------------- ### Dynamic Host Grouping with group_by Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/tips_tricks/ansible_tips_tricks.rst Shows how to use the group_by module to create dynamic inventory groups based on OS facts, and how to target those groups in subsequent plays. ```yaml - name: Create dynamic group based on OS hosts: all tasks: - group_by: key: os_{{ ansible_distribution }} ``` ```yaml - name: Run tasks on CentOS hosts hosts: os_CentOS tasks: - debug: msg: "Running on CentOS" ``` -------------------------------- ### Deprecating a Module in Ansible Core Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/dev_guide/module_lifecycle.rst To deprecate a module in ansible-core, rename its file to start with an underscore, update the changelog, reference the deprecation in the porting guide, and add deprecation details to its documentation. ```yaml deprecated: removed_in: "2.10" why: "This module is outdated and replaced by a newer implementation." alternatives: "Use M(whatmoduletouseinstead) instead." ``` -------------------------------- ### Exact Module Match Query Example Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/dev_guide/developing_collections_resource_reporting.rst Example of a query file entry using an exact module Fully Qualified Collection Name (FQCN) as the key. ```yaml community.general.ipify_facts: name: "{{ ip_address }}" canonical_facts: ip_address: "{{ ip_address }}" facts: device_type: "ip_address" ``` -------------------------------- ### Install OpenSSH Server and Configure Firewall on Windows Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/os_guide/windows_ssh.rst This PowerShell script installs the OpenSSH server capability, sets the sshd service to start automatically, and configures the Windows firewall to allow inbound TCP connections on port 22. It also sets the default shell for SSH connections to PowerShell. ```powershell Get-WindowsCapability -Name OpenSSH.Server* -Online | Add-WindowsCapability -Online Set-Service -Name sshd -StartupType Automatic -Status Running $firewallParams = @{ Name = 'sshd-Server-In-TCP' DisplayName = 'Inbound rule for OpenSSH Server (sshd) on TCP port 22' Action = 'Allow' Direction = 'Inbound' Enabled = 'True' # This is not a boolean but an enum Profile = 'Any' Protocol = 'TCP' LocalPort = 22 } New-NetFirewallRule @firewallParams $shellParams = @{ Path = 'HKLM:\SOFTWARE\OpenSSH' Name = 'DefaultShell' Value = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' PropertyType = 'String' Force = $true } New-ItemProperty @shellParams ``` -------------------------------- ### Create PostgreSQL Info Target Directories Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/community/collection_contributors/collection_integration_add.rst Create the necessary directory structure for the postgresql_info target. ```bash mkdir -p tests/integration/targets/postgresql_info/tasks tests/integration/targets/postgresql_info/meta ``` -------------------------------- ### Remove Installed Ansible Role (Bash) Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/galaxy/user_guide.rst Deletes a specified role from the Ansible roles path. Ensure the role name is in the correct 'namespace.role_name' format before execution. ```bash $ ansible-galaxy role remove namespace.role_name ``` -------------------------------- ### Defining Group and Host Variables Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/tips_tricks/sample_setup.rst Examples of YAML files used to define configuration variables for specific groups or individual hosts. These files are typically located in group_vars/ or host_vars/ directories. ```yaml --- # file: group_vars/atlanta ntp: ntp-atlanta.example.com backup: backup-atlanta.example.com ``` ```yaml --- # file: group_vars/webservers apacheMaxRequestsPerChild: 3000 apacheMaxClients: 900 ``` ```yaml --- # file: group_vars/all ntp: ntp-boston.example.com backup: backup-boston.example.com ``` ```yaml --- # file: host_vars/db-bos-1.example.com foo_agent_port: 86 ``` -------------------------------- ### Standard Ansible Directory Layout Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/tips_tricks/sample_setup.rst A common directory structure for Ansible projects where inventory files, group variables, and playbooks are organized at the root level. This layout is suitable for small to medium-sized automation projects. ```console production # inventory file for production servers staging # inventory file for staging environment group_vars/ group1.yml # here we assign variables to particular groups group2.yml host_vars/ hostname1.yml # here we assign variables to particular systems hostname2.yml library/ # if any custom modules, put them here (optional) module_utils/ # if any custom module_utils to support modules, put them here (optional) filter_plugins/ # if any custom filter plugins, put them here (optional) site.yml # main playbook webservers.yml # playbook for webserver tier dbservers.yml # playbook for dbserver tier tasks/ # task files included from playbooks webservers-extra.yml # <-- avoids confusing playbook with task files ``` -------------------------------- ### Initialize Collection with Custom Skeleton and Extra Variables Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/dev_guide/developing_collections_creating.rst Use this command to create a new collection from a custom skeleton directory, passing additional variables from a JSON file. ```bash ansible_collections#> ansible-galaxy collection init --collection-skeleton /path/to/my/namespace/skeleton --extra-vars "@my_vars_file.json" my_namespace.my_collection ``` -------------------------------- ### Configure IIS Website with DSC Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/os_guide/windows_dsc.rst Automates the installation of IIS features, creation of web content, and setup of a new website with specific bindings and authentication settings. ```yaml+jinja - name: Install xWebAdministration module win_psmodule: name: xWebAdministration state: present - name: Install IIS features that are required win_dsc: resource_name: WindowsFeature Name: '{{ item }}' Ensure: Present loop: - Web-Server - Web-Asp-Net45 - name: Setup web content win_dsc: resource_name: File DestinationPath: C:\inetpub\IISSite\index.html Type: File Contents: | IIS Site This is the body Ensure: present - name: Create new website win_dsc: resource_name: xWebsite Name: NewIISSite State: Started PhysicalPath: C:\inetpub\IISSite\index.html BindingInfo: - Protocol: https Port: 8443 CertificateStoreName: My CertificateThumbprint: C676A89018C4D5902353545343634F35E6B3A659 HostName: DSCTest IPAddress: '*' SSLFlags: 1 - Protocol: http Port: 8080 IPAddress: '*' AuthenticationInfo: Anonymous: false Basic: true Digest: false Windows: true ``` -------------------------------- ### Setup Ansible Development Environment (Fish) Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/installation_guide/intro_installation.rst Sets up the environment variables for running Ansible from a source clone using the Fish shell. This is necessary for development and testing. ```console $ source ./hacking/env-setup.fish ``` -------------------------------- ### Get Documentation for a Specific Strategy Plugin Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/plugins/strategy.rst This command retrieves detailed documentation and examples for a specific strategy plugin. Replace '' with the actual name of the plugin you want to inspect. ```shell ansible-doc -t strategy ``` -------------------------------- ### Import Playbooks for Infrastructure Organization (YAML) Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/tips_tricks/sample_setup.rst This playbook imports other playbooks to define infrastructure configuration. It demonstrates a top-level playbook that orchestrates the deployment of webservers and database servers. ```yaml --- # file: site.yml - import_playbook: webservers.yml - import_playbook: dbservers.yml ``` ```yaml --- # file: webservers.yml - hosts: webservers roles: - common - webtier ``` -------------------------------- ### Update Read the Docs Python Version (YAML) Source: https://github.com/ansible/ansible-documentation/blob/devel/MAINTAINERS.md Specifies the Python version for Read the Docs build environments. This example shows setting the Python version to 3.11 for Ubuntu LTS. ```yaml build: os: ubuntu-lts-latest tools: python: >- 3.11 ``` -------------------------------- ### Ansible 2.3: Named blocks in playbooks Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/porting_guides/porting_guide_2.3.rst Shows how to use named blocks in Ansible playbooks starting from version 2.3. This feature allows for better organization and avoids the need for extensive comments. ```yaml - name: Block test case hosts: localhost tasks: - name: Attempt to setup foo block: - debug: msg='I execute normally' - command: /bin/false - debug: msg='I never execute, cause ERROR!' rescue: - debug: msg='I caught an error' - command: /bin/false - debug: msg='I also never execute :-(' always: - debug: msg="this always executes" ``` -------------------------------- ### Define an Example Block in Ansible Module Documentation Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/dev_guide/developing_modules_documenting.rst This Python string defines an example block for an Ansible module, demonstrating how to structure a playbook-ready example with a name and module usage. ```text EXAMPLES = r''' - name: Ensure foo is installed namespace.collection.modulename: name: foo state: present ''' ``` -------------------------------- ### Ansible Task and Handler Configuration (YAML) Source: https://github.com/ansible/ansible-documentation/blob/devel/docs/docsite/rst/tips_tricks/sample_setup.rst This snippet shows a typical Ansible role structure, including tasks and handlers. The tasks configure NTP installation and service, while the handler restarts the NTP service when notified. ```yaml --- # file: roles/common/tasks/main.yml - name: be sure ntp is installed yum: name: ntp state: present tags: ntp - name: be sure ntp is configured template: src: ntp.conf.j2 dest: /etc/ntp.conf notify: - restart ntpd tags: ntp - name: be sure ntpd is running and enabled ansible.builtin.service: name: ntpd state: started enabled: true tags: ntp ``` ```yaml --- # file: roles/common/handlers/main.yml - name: restart ntpd ansible.builtin.service: name: ntpd state: restarted ```