Aide-mémoire Ansible

Référence consultable des commandes Ansible : commandes ad-hoc, playbooks, rôles, modèles, handlers, boucles, Vault et Galaxy, avec chaque paramètre expliqué.

S’exécute dans votre navigateur · rien n’est envoyéNouveau

39 commandes

Setup & info

ansible --versionShow the installed Ansible version, Python version and the path to the active config file.

Useful to confirm which ansible.cfg is actually being loaded, since Ansible searches several locations (ANSIBLE_CONFIG, ./ansible.cfg, ~/.ansible.cfg, /etc/ansible/ansible.cfg) in that order.

ansible-config dumpShow every active configuration setting, including defaults.

Exemple

ansible-config dump --only-changed

Options

--only-changedShow only the settings you have changed from their default value.
-c <file>Use a specific config file instead of the one Ansible would normally find.
ansible-doc <module>Show documentation for a module, including its parameters and examples.

Exemple

ansible-doc ansible.builtin.copy

Options

-lList all available modules.
-t moduleLimit to module documentation (the default; also accepts lookup, filter, etc.).
-sShow a short "snippet" form ready to paste into a playbook.
-FShow every plugin name and which file it comes from.

Inventory

ansible-inventory --listShow the full inventory as JSON, with all groups, hosts and variables resolved.

Useful for checking what Ansible actually sees after merging static files, dynamic inventory plugins and group/host variable files.

ansible-inventory --graphShow groups and hosts as a tree, without the variables.

Exemple

ansible-inventory --graph --vars

Options

--varsAlso show the variables for each host and group.
ansible <pattern> --list-hostsList the hosts that a pattern matches, without running anything against them.

A quick way to check a pattern is correct before you run it for real. "all" matches every host; a group name matches that group; "web*" matches by wildcard.

Exemple

ansible web --list-hosts
[group]\nhost ansible_host=<ip>Basic structure of a static INI-style inventory file.

A group header in brackets, then one host per line with optional connection variables. "[all:vars]" sets variables for every host, and "[prod:children]" builds a group out of other groups.

Exemple

[web]
web1 ansible_host=192.168.1.21

[all:vars]
ansible_user=ubuntu
ansible_python_interpreter=/usr/bin/python3

[prod:children]
web
db

Ad-hoc commands

ansible all -m ansible.builtin.pingCheck that Ansible can connect to and run Python on every host in the inventory.

This does not test network connectivity (ICMP); it confirms SSH access and a working Python interpreter, which is what every other module needs.

Options

-i <file>Use a specific inventory file instead of the default one.
-i 'host,'Use an inline inventory (note the trailing comma for a single host).
ansible <pattern> -m <module> -a "<args>"Run a single module against matching hosts without writing a playbook.

Good for one-off checks and fixes. For anything you will run more than once, write a playbook instead so it is repeatable and version-controlled.

Exemple

ansible web -m ansible.builtin.apt -a "name=apache2 state=present" -b -K

Options

-m <module>Module to run, for example ansible.builtin.apt, ansible.builtin.copy, ansible.builtin.service.
-a "<args>"Module arguments as a space-separated key=value string.
-bUse become to execute with elevated privileges (like sudo).
-KPrompt for the become (privilege escalation) password.
-u <user>Connect over SSH as this user.
-kPrompt for the SSH password instead of using key-based auth.
ansible all -m ansible.builtin.setupCollect and display system facts (OS, IP addresses, memory, CPU, mounted filesystems) from each host.

Exemple

ansible web -m ansible.builtin.setup -a "filter=ansible_distribution*"

Options

-a "filter=<pattern>"Only show facts whose name matches this wildcard pattern.
ansible all -m ansible.builtin.reboot -bReboot matching hosts and wait for them to come back online.
Attention: This restarts every matched host. Double-check the pattern (especially with "all") before running it, and consider --limit to narrow it down first.

Playbooks

ansible-playbook <playbook>.ymlRun a playbook against the hosts and groups it targets.

Exemple

ansible-playbook -i inventory.ini -u deploy -b -K site.yml

Options

-i <file>Inventory file to use for the pattern in the playbook.
-u <user>Connect over SSH as this user.
-kAsk for the SSH password.
-f <n>Number of parallel forks (hosts processed at the same time). Default is 5.
-T <seconds>Connection timeout in seconds.
-t <tag>Only run tasks (and plays) tagged with this tag.
--skip-tags <tag>Run everything except tasks tagged with this tag.
-M <path>Load local modules from this path, in addition to the built-in ones.
-bExecute with elevated privileges (uses become, like sudo).
-KPrompt for the become password.
ansible-playbook <playbook>.yml --checkDry run: show what would change without actually making any changes.

Not every module supports check mode equally well; some report "changed" conservatively when they cannot be sure. Combine with --diff to see the actual content differences for file-based tasks.

Options

--diffShow a before/after diff for tasks that change file content or templates.
ansible-playbook <playbook>.yml --limit <pattern>Restrict a playbook run to a subset of the hosts it would otherwise target.

The pattern is checked against hosts already selected by the play's own "hosts:" line; it narrows that selection, it does not add hosts outside it.

Exemple

ansible-playbook site.yml --limit "web1,web2"
ansible-playbook <playbook>.yml --stepConfirm interactively before each task runs.

Useful while writing or debugging a new playbook, to see exactly where something goes wrong without waiting for the whole run to fail.

ansible-playbook <playbook>.yml --list-tasksList every task the playbook would run, with its tags, without running anything.

Options

--list-tagsList the available tags instead of tasks.
--list-hostsList the hosts the playbook would target.
ansible-playbook <playbook>.yml --syntax-checkCheck the playbook YAML for syntax errors without connecting to any host or running anything.

The fastest sanity check before a real run, and safe to use in CI.

ansible-playbook <playbook>.yml -vShow more detail in the output, including the result of each module call.

Repeat the flag for more detail: -vv adds connection information, -vvv adds raw SSH and module arguments, -vvvv enables plugin-level debugging. -vvv is a reasonable starting point for diagnosing a failing task.

Options

-vBasic extra output.
-vvvConnection and module argument detail, good for most troubleshooting.
-vvvvMaximum detail, including plugin loading.

Vault

ansible-vault create secrets.ymlCreate a new file, encrypted with AES256, and open it in your editor.

Ansible Vault lets you keep secrets (passwords, API keys, certificates) in the same repository as your playbooks, as ciphertext instead of plain text.

Options

--vault-id <label@source>Use a named vault identity, so different files can be encrypted with different passwords.
--ask-vault-passPrompt for the password instead of reading it from a file.
--vault-password-file <file>Read the password from this file (or script, if executable).
ansible-vault encrypt <file>Encrypt an existing plaintext file in place.

Exemple

ansible-vault encrypt group_vars/prod/vault.yml
Attention: This overwrites the file with its encrypted form. Make sure you have the content committed or backed up before encrypting, in case you need the original plaintext again.
ansible-vault decrypt <file>Decrypt a file in place, turning it back into plain text.
Attention: The file becomes plain text on disk. Do not commit it in this state if it still contains real secrets.
ansible-vault view <file>Print the decrypted content to the terminal without writing a plaintext file to disk.

The safer way to just read a secret without risking an accidental plaintext commit.

ansible-vault edit <file>Decrypt, open in your editor, and re-encrypt on save, without leaving a plaintext file behind.

The preferred way to make a small change to an encrypted file; combining separate decrypt/edit/encrypt steps risks leaving plaintext on disk if you forget the last step.

ansible-vault rekey <file>Change the password used to encrypt a file.

Needed when a vault password may have leaked, or when rotating secrets as part of regular hygiene.

ansible-vault encrypt_string '<value>' --name '<var_name>'Encrypt a single value (not a whole file) for pasting directly into a playbook or variables file.

Produces a "!vault |" YAML block you can paste inline, so most of a variables file can stay in plain text while only the sensitive value is encrypted.

Exemple

ansible-vault encrypt_string 'S3cretPass!' --name 'db_password'
ansible-playbook <playbook>.yml --ask-vault-passRun a playbook that references vault-encrypted files or variables, prompting for the password.

Options

--ask-vault-passPrompt for the vault password interactively.
--vault-password-file <file>Read the vault password from a file or script instead of prompting.

Galaxy

ansible-galaxy collection install <namespace.collection>Download and install a collection of modules, roles and plugins from Ansible Galaxy.

Downloads from the configured Galaxy server (galaxy.ansible.com by default) unless a different server is set in ansible.cfg.

Exemple

ansible-galaxy collection install community.general
ansible-galaxy collection install -r requirements.ymlInstall every collection (and optionally role) listed in a requirements.yml file.

The standard way to pin and reproduce the exact set of collections a project depends on, instead of installing them one at a time.

ansible-galaxy collection listList every collection installed, and where each one was installed from.

Useful to check whether a collection came from the project-local collections path or a system-wide one, since Ansible searches several locations in order.

ansible-galaxy role install <namespace.role>Download and install a role from Ansible Galaxy into ~/.ansible/roles by default.

Exemple

ansible-galaxy role install geerlingguy.nginx

Options

-p <path>Install into a specific path instead of the default roles directory.
ansible-galaxy role listList every role currently installed.

Lists roles installed via ansible-galaxy, not roles that simply exist as plain directories under a project's roles/ folder.

ansible-galaxy init <role_name>Scaffold a new role with the standard directory structure (tasks, handlers, templates, defaults, meta).

Creates the folders Ansible expects for a role, with placeholder files, so you do not have to remember the exact layout by hand.

Playbook logic & templates

- name: <task> <module>: ... when: <condition>Run a task only when a condition is true, based on a variable, fact, or a previous task's registered result.

The condition is plain Jinja2, without the {{ }} delimiters needed elsewhere. Multiple when conditions in a list are combined with AND.

Exemple

- name: Install Apache on Debian family
  ansible.builtin.apt:
    name: apache2
    state: present
  when: ansible_facts['os_family'] == "Debian"
- name: <task> <module>: "{{ item }}" loop: <list>Run a task once for each item in a list.

loop is the modern replacement for the older with_<lookup> syntax (with_items, with_dict, and so on), which still works but is no longer the recommended form.

Exemple

- name: Create directories
  ansible.builtin.file:
    path: "/data/{{ item }}"
    state: directory
  loop:
    - logs
    - uploads
    - cache

Options

loop_control.labelControl what is shown in the task output per iteration, useful when looping over large/complex dictionaries.
loop_control.pauseWait a number of seconds between iterations.
- name: <task> <module>: ... register: <var>Capture the result of a task (success/failure, output, return values) into a variable for use in later tasks.

Exemple

- name: Check if file exists
  ansible.builtin.stat:
    path: /etc/myapp/config.yml
  register: config_file

- name: Create default config
  ansible.builtin.copy:
    src: default-config.yml
    dest: /etc/myapp/config.yml
  when: not config_file.stat.exists
tasks: - name: <task> <module>: ... notify: <handler-name> handlers: - name: <handler-name> <module>: ...A handler is a task that only runs when notified by another task, typically used to restart or reload a service after a config change.

By default, handlers run once at the end of the play (or at explicit flush points), even if notified by several tasks, so a service is reloaded once no matter how many config files changed.

Exemple

tasks:
  - name: Deploy nginx config
    ansible.builtin.template:
      src: nginx.conf.j2
      dest: /etc/nginx/nginx.conf
    notify: Reload nginx
handlers:
  - name: Reload nginx
    ansible.builtin.service:
      name: nginx
      state: reloaded
- name: <task> ansible.builtin.template: src: <file>.j2 dest: <path>Render a Jinja2 template file, substituting variables and facts, and copy the result to the target host.

Unlike ansible.builtin.copy, template always processes the file through the Jinja2 engine first; any {{ }} or {% %} in the source file is evaluated, not copied literally.

Exemple

# nginx.conf.j2
server {
  listen {{ http_port }};
  server_name {{ inventory_hostname }};
}

Options

validate "<command> %s"Run a validation command against the rendered file before it replaces the real destination, for example "nginx -t -c %s".
backup: trueKeep a timestamped backup of the previous file before overwriting it.
roles/<role_name>/{tasks,handlers,templates,files,vars,defaults,meta}/The standard directory layout Ansible expects for a role: each subfolder has a specific purpose and only needs a main.yml if that feature is used.

tasks/main.yml is the entry point; handlers/main.yml holds handlers; templates/ and files/ hold the respective source files (found automatically by template/copy without a full path, from within the role); defaults/main.yml holds overridable default variables (lowest precedence); vars/main.yml holds role variables (higher precedence, not meant to be overridden by callers).

Options

defaults/main.ymlDefault values, easily overridden by the playbook or inventory.
vars/main.ymlRole-internal variables, higher precedence, not intended for external overriding.
meta/main.ymlRole metadata and dependencies on other roles.
- hosts: <group> roles: - <role_name> - role: <role_name> vars: <key>: <value>Apply a role to a play, optionally overriding its default variables.

ansible.builtin.include_role (used as a task, not at the play level) applies a role conditionally or partway through a task list instead of always at play start, which the simpler "roles:" list does not support.

Les descriptions de cette référence sont pour l’instant en anglais.

Explication

Recherchez ou filtrez par groupe et copiez une commande en un clic. Ouvrez une commande pour voir ce qu’elle fait, un exemple et chaque paramètre qu’elle accepte, avec des avertissements là où elle affecte chaque hôte correspondant.

🔒 Votre saisie reste dans votre navigateur et n’est envoyée nulle part.

Questions fréquentes

Que fait --check dans ansible-playbook ?

Elle effectue un essai à blanc : Ansible indique ce qu’elle changerait sans rien modifier réellement. Combinez-la avec --diff pour voir les différences de contenu sur les tâches basées sur des fichiers.

Quelle est la différence entre un handler et une tâche normale ?

Un handler ne s’exécute que lorsqu’une autre tâche le notifie explicitement (généralement pour redémarrer ou recharger un service après un changement de configuration), et s’exécute par défaut une seule fois à la fin de la play même s’il est notifié plusieurs fois.

Et ensuite ?

Plus dans cette section

  • Aide-mémoire AWS CLIRéférence consultable AWS CLI : configuration, S3, EC2, VPC/Route 53, CloudWatch, Lambda, ECR/ECS, IAM et CloudFormation, avec chaque option expliquée.
  • Aide-mémoire Azure CLIRéférence consultable des commandes Azure CLI : connexion, groupes de ressources, VM, stockage, applications web et AKS, avec chaque paramètre expliqué.

Aussi utile

  • Aide-mémoire des commandes LinuxListe consultable des commandes Linux essentielles : fichiers, permissions, texte, processus, services, réseau et utilisateurs.
  • Analyseur de manifestes KubernetesCollez un manifeste Kubernetes pour repérer des limites de ressources manquantes, des réglages de sécurité risqués, des règles RBAC trop larges, et obtenir un patch suggéré.
  • Générateur d’expression cronCréez une expression cron à 5 champs via un formulaire (minute, heure, jour, mois, jour de la semaine), avec une explication en langage clair et les 5 prochaines exécutions.

Un problème ou une suggestion ? Dites-le-nous