Tech & DevOps HubEspace Tech & DevOps

Explorez le monde du Dev, du Cloud et des outils DevOps à travers nos articles et discussions Explore the world of development, the cloud and DevOps tools
 FR      EN
Ansible
Général
Debug a custom variable
ansible localhost -m debug -a "msg={{ my_var }}"

Prints the value of a variable to help diagnose issues.
If my_var is defined (for example, set to “Hello World”):
localhost | SUCCESS => { “changed”: false, “msg”: “Hello World” }
Define the Variable on the Command Line:
Pass the variable definition using the -e flag (extra vars): ansible localhost -m debug -a "msg={{ my_var }}" -e "my_var=Hello_World_From_CLI" This command injects the value of my_var into the variable before executing the task.
Run in dry-run mode
ansible-playbook --check --diff site.yml

Simulates execution without applying any changes.
Specifically:
  • Ansible will connect to the hosts and evaluate what the final state should be (for example, “this file should exist with this content” or “this package should be installed”).
  • It indicates which tasks would have resulted in a change (marked as changed=true in yellow in the result) and which would have been ignored (marked in green).
  • Files are not copied, packages are not installed, services are not restarted, and commands are not executed on remote hosts.

Add the --diff option to display the exact lines of code, configuration or template files that will be modified on the server (as a green/red diff)
! Important limitations:
  • Conditional tasks: If task B depends on the result or a file created by task A, the --check mode may fail task B because task A has not actually created the file.
  • The shell / command module: Ansible cannot guess what a raw script does. By default, these modules are ignored in simulation mode, unless you force them to run by adding check_mode: false to the task.
Run in verbose mode
ansible-playbook site.yml -vvv

Executes the playbook with detailed verbose output.
At the -vvv level, the output typically includes:
  • Task details: Detailed information about the modules called and the exact arguments passed to them.
  • Module arguments: The specific parameters used for each task.
  • Connection details: Information about the SSH connection process used for each host (e.g., username, connection method, port).
  • Module output: The raw output returned by the remote operating system when a module executes a command (e.g., the output of apt or yum installations).

When a task fails, -vvv is essential for seeing the specific error message returned by the remote host or module, rather than just the generic “FAIL!” message.
Understanding the flow helps advanced users precisely track how Ansible analyzes tasks, processes facts, and executes commands in sequence.
Use sudo password
ansible-playbook site.yml --ask-become-pass

Runs the specified playbook (site.yml) and prompts the user to enter the password required to run tasks with elevated privileges (e.g., sudo).
Validate playbook syntax
ansible-playbook site.yml --syntax-check

Checks the YAML syntax and structure of the playbook.
To go beyond basic syntax and check for best practices (such as missing `become` permissions or the use of deprecated modules), use the "ansible-lint" dedicated tool ansible-lint site.yml
Show effective Ansible configuration
ansible-config dump

Displays all configuration settings currently used by the environment.
It performs several actions to collect this information:
  • Read priority: indicates where to look for the configuration
    (current directory ansible.cfg, ~/.ansible.cfg, /etc/ansible/ansible.cfg).
  • Checks environment variables: It reads all relevant environment variables
    (e.g., ANSIBLE_INVENTORY, ANSIBLE_VERBOSITY).
  • Merge and display: It combines all results, applies the appropriate priority rules, and displays the final, effective configuration values in a clear format.

Main use cases:
  • Troubleshooting: This is the primary tool for debugging why Ansible is behaving in a certain way (e.g., why it is looking in the wrong inventory file or using the wrong default user).
  • Verification: This confirms precisely which settings are active in your current session.
Galaxy Collection
Install multiple collections using requirements.yml
ansible-galaxy collection install -r requirements.yml

Install multiple Ansible collections listed in a specified YAML file.
Facilitates dependency management in CI/CD.
For the command to work, the file must target the "collections" key with the exact name and, optionally, the version of the packages:
---
collections:
  - name: community.docker
    version: 3.11.0
  - name: amazon.aws

Force the update: use --force
To bypass SSL validation: Useful if restrictive proxies, add --ignore-certs
Install a collection
ansible-galaxy collection install community.docker

Downloads and installs the specified Ansible Galaxy collection: community.docker
To view the full list of included modules (such as docker_container or docker_image), visit the community.docker documentation page on Ansible Docs.
List all installed collections
ansible-galaxy collection list

This is the default command and will show all collections in the standard search paths.
You can list a specific collection by adding its fully qualified collection name to the command: ansible-galaxy collection list namespace.collection_name
Use flags like -p to search in other directories: ansible-galaxy collection list -p /path/to/collections
Use -vvv for more detailed information. ansible-galaxy collection list -vvv
These commands works for collections installed from Galaxy, private hubs, or local sources, and it will also show collections under development.
Search for a collection
ansible-galaxy collection search community.docker

#ansible-galaxy collection search namespace.keyword
Searches the Ansible Galaxy online catalog and returns matching collections.
To find the collection via l'UI, do a search with namespace:'community' and keyword:'docker', url: community.docker sur Galaxy
Remove a collection
ansible-galaxy collection list -vvv
cd ~/.ansible/collections/ansible_collections/community/docker
rm -rf ~/.ansible/collections/ansible_collections/community/docker

The ansible-galaxy CLI has no remove command. Manual folder deletion is required.
1. Check paths: ansible-galaxy collection list -vvv
2. Delete: Linux/macOS: rm -rf ~/.ansible/collections/ansible_collections/community/docker Windows: rmdir /s /q %HOMEPATH%\.ansible\collections\ansible_collections\community\docker
Check an installed collection
ansible-galaxy collection list community.docker

Displays specific information about the locally installed community.docker collection. If the collection is installed, the output displays the collection name, its installed version, and the installation path.
/home/user/.ansible/collections/ansible_collections Collection Version ------------------- ------- community.docker 3.13.10 # (Version number will vary)
Galaxy Rôle
Initialize a new role
ansible-galaxy init myrole

Creates a complete skeleton following the recommended structure for a new Ansible role named myrole
Add -p myrolesdir (or --init-path myrolesdir) which specifies the parent directory in which the new role folder should be created (here the "myrolesdir" folder)
Add --offline to disable the creation of empty folders and generate only the essential files.
The directory structure created contains configuration files pre-filled with empty comments for each component
Install roles using requirements.yml
ansible-galaxy install -r requirements.yml

A global command that, similar to collections, automatically installs all Ansible dependencies (primarily roles, and sometimes collections depending on your version) listed in a named configuration file.
The command ansible-galaxy install -r ... historically targets roles.
For collections, use:ansible-galaxy collection install -r requirements.yml
By default, Ansible ignores roles that have already been downloaded.
To update them, add the --force option.
Change the installation directory: use the -p or --roles-path option
Install a role from Galaxy
ansible-galaxy install geerlingguy.mysql

Downloads and installs the role geerlingguy.mysql from the official Ansible Galaxy platform. By default, it installs in the user directory (~/.ansible/roles/geerlingguy.mysql)
To install it directly in your current project folder, add the option: -p ./roles/
Force an update with the option: --force if the role is already installed and you want the latest version
Search for a role
ansible-galaxy role search mysql

List the corresponding roles on Galaxy.
As with collections, you can search for roles with:
keyword: mysql and/or with: namespace: geerlingguy *
See the URL: https://galaxy.ansible.com/ui/standalone/roles/?page=1&page_size=10&sort=-created&keywords=mysql&namespace=geerlingguy
* Jeff Geerling is an authority on infrastructure automation and DevOps practices.
Remove a role
rm -rf ~/.ansible/roles/geerlingguy.mysql

Removes the role locally.
You can also use: ansible-galaxy role remove geerlingguy.mysql
View role directory structure
tree roles/

Displays the standard directory layout of an Ansible role.
tree: Command-line utility that generates a file and directory tree listing.
roles/: Common directory name where Ansible looks for roles. It contains subdirectories, each representing a single role.
For Windows; you will need to put the file path surrounded by “...” (double quote)
Ubuntu/Debian : sudo apt install tree

Mac: brew install tree
Hosts
Run an ad hoc command on hosts
ansible all -i inventory.ini -m ping

The Ansible ping module performs several crucial checks via SSH (or WinRM for Windows hosts)
SSH connectivity: It verifies that the Ansible control node can successfully connect to the target host using the configured credentials (usually SSH keys).
Python availability: It attempts to run a small Python script on the remote machine to ensure that a usable Python interpreter is available.
Returns “pong”: If connectivity and Python availability are confirmed, the target host returns a “pong” message, indicating a successful connection.
#output: host1.example.com | SUCCESS => { “changed”: false, “ping”: “pong” } host2.example.com | SUCCESS => { “changed”: false, “ping”: “pong” }
If a host is unreachable, the output will indicate an UNREACHABLE! status, often due to SSH configuration issues, incorrect credentials, or network problems.
This command serves as a fundamental first step in troubleshooting and validating an Ansible environment before running more complex playbooks.
Limit execution to one host
ansible-playbook site.yml -l myserver

Runs the specified playbook (site.yml), but limits its execution only to the host (or group) matching the template (myserver) configured in the inventory.
Useful for targeted testing.
List inventory hosts
ansible-inventory -i inventory.ini --list

Analyzes the specified inventory file (inventory.ini) and displays all host and group information in JSON format.
Particularly useful for debugging, verifying inventory structure, and confirming how dynamic inventory plugins interpret source data.
Show host variables
ansible -i inventory.ini myserver -m debug -a "var=hostvars[inventory_hostname]"

Displays all variables and facts accumulated for the specific host (named myserver), as interpreted by Ansible from the configuration and inventory file (inventory.ini).
SSH
Change SSH user
ansible-playbook site.yml -u devops

Runs tasks using a different SSH user than the default.
This -u flag controls the initial login user. This does not automatically grant administrative privileges (such as sudo or root access).
If the playbook tasks require root permissions (e.g., installing software, modifying system files), the playbook must explicitly use the become: true directive in the YAML file, or add the --become (or -b) flag to the command line.
Test SSH connection
ansible all -m ping

Tests connectivity to all hosts defined in its inventory, it does not run a playbook.
The purpose of this command is to verify basic connectivity (SSH authentication and presence of Python)
Tags
Skip a tag
ansible-playbook site.yml --skip-tags "debug"

Skips tasks associated with a given tag.
Use a specific tag
ansible-playbook site.yml --tags "install"

Runs the playbook but limits execution to only those tasks, blocks, or roles that have been explicitly assigned the “install” label in the YAML file.