Ansible cheatsheet

Doorzoekbare Ansible-commandoreferentie: ad-hoc commando’s, playbooks, roles, templates, handlers, loops, Vault en Galaxy, met elke parameter uitgelegd.

Draait in je browser · er wordt niets verstuurdNieuw

39 commando’s

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.

Voorbeeld

ansible-config dump --only-changed

Opties

--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.

Voorbeeld

ansible-doc ansible.builtin.copy

Opties

-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.

Voorbeeld

ansible-inventory --graph --vars

Opties

--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.

Voorbeeld

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.

Voorbeeld

[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.

Opties

-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.

Voorbeeld

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

Opties

-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.

Voorbeeld

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

Opties

-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.
Let op: 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.

Voorbeeld

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

Opties

-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.

Opties

--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.

Voorbeeld

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.

Opties

--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.

Opties

-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.

Opties

--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.

Voorbeeld

ansible-vault encrypt group_vars/prod/vault.yml
Let op: 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.
Let op: 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.

Voorbeeld

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.

Opties

--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.

Voorbeeld

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.

Voorbeeld

ansible-galaxy role install geerlingguy.nginx

Opties

-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.

Voorbeeld

- 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.

Voorbeeld

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

Opties

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.

Voorbeeld

- 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.

Voorbeeld

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.

Voorbeeld

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

Opties

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).

Opties

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.

De omschrijvingen in dit naslagwerk zijn voorlopig in het Engels.

Uitleg

Zoek of filter op groep en kopieer een commando met één klik. Open een commando voor uitleg, een voorbeeld en elke parameter die het accepteert, met waarschuwingen waar het invloed heeft op elke gematchte host.

🔒 Je invoer blijft in je browser en wordt nergens naartoe gestuurd.

Veelgestelde vragen

Wat doet --check in ansible-playbook?

Het voert een dry run uit: Ansible rapporteert wat het zou veranderen zonder iets daadwerkelijk te wijzigen. Combineer met --diff om de inhoudelijke verschillen te zien voor bestandsgerichte taken.

Wat is het verschil tussen een handler en een gewone taak?

Een handler draait alleen wanneer een andere taak hem expliciet notify’t (meestal om een service te herstarten of herladen na een configwijziging), en draait standaard één keer aan het einde van de play, ook als meerdere taken hem aanroepen.

Wat nu?

Meer in dit onderdeel

  • AWS CLI cheatsheetDoorzoekbare AWS CLI-referentie: setup, S3, EC2, VPC/Route 53, CloudWatch, Lambda, ECR/ECS, IAM en CloudFormation, met elke optie uitgelegd.
  • Azure CLI cheatsheetDoorzoekbare Azure CLI-commandoreferentie: login, resourcegroepen, VM’s, opslag, webapps en AKS, met elke parameter uitgelegd.

Ook handig

  • Linux-commando’s cheatsheetDoorzoekbare lijst met essentiële Linux-commando’s voor bestanden, rechten, tekst, processen, services, netwerk en gebruikers.
  • Kubernetes manifest analyzerPlak een Kubernetes-manifest om ontbrekende resource-limieten, risicovolle beveiligingsinstellingen en te brede RBAC-regels te vinden, met een voorgestelde patch.
  • Cron-expressiebouwerBouw een cron-expressie met 5 velden via een formulier (minuut, uur, dag, maand, weekdag), bekijk een uitleg in gewone taal en de volgende 5 uitvoeringstijden.

Een probleem gevonden of een suggestie? Laat het ons weten