Ansible Cheat Sheet
Durchsuchbare Ansible-Befehlsreferenz: Ad-hoc-Befehle, Playbooks, Roles, Templates, Handler, Loops, Vault und Galaxy, mit jedem Parameter erklärt.
Läuft im Browser · es wird nichts gesendetNeu
39 Befehle
Setup & info
ansible --versionShow the installed Ansible version, Python version and the path to the active config file.
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.
ansible-config dumpShow every active configuration setting, including defaults.Beispiel
ansible-config dump --only-changed
Optionen
--only-changed | Show 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.
ansible-doc <module>Show documentation for a module, including its parameters and examples.Beispiel
ansible-doc ansible.builtin.copy
Optionen
-l | List all available modules. |
|---|---|
-t module | Limit to module documentation (the default; also accepts lookup, filter, etc.). |
-s | Show a short "snippet" form ready to paste into a playbook. |
-F | Show 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.
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.
ansible-inventory --graphShow groups and hosts as a tree, without the variables.Beispiel
ansible-inventory --graph --vars
Optionen
--vars | Also show the variables for each host and group. |
|---|
ansible <pattern> --list-hostsList the hosts that a pattern matches, without running anything against them.
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.
Beispiel
ansible web --list-hosts
[group]\nhost ansible_host=<ip>Basic structure of a static INI-style inventory file.
[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.
Beispiel
[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.
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.
Optionen
-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.
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.
Beispiel
ansible web -m ansible.builtin.apt -a "name=apache2 state=present" -b -K
Optionen
-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. |
-b | Use become to execute with elevated privileges (like sudo). |
-K | Prompt for the become (privilege escalation) password. |
-u <user> | Connect over SSH as this user. |
-k | Prompt 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.
ansible all -m ansible.builtin.setupCollect and display system facts (OS, IP addresses, memory, CPU, mounted filesystems) from each host.Beispiel
ansible web -m ansible.builtin.setup -a "filter=ansible_distribution*"
Optionen
-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.
ansible all -m ansible.builtin.reboot -bReboot matching hosts and wait for them to come back online.Playbooks
ansible-playbook <playbook>.ymlRun a playbook against the hosts and groups it targets.
ansible-playbook <playbook>.ymlRun a playbook against the hosts and groups it targets.Beispiel
ansible-playbook -i inventory.ini -u deploy -b -K site.yml
Optionen
-i <file> | Inventory file to use for the pattern in the playbook. |
|---|---|
-u <user> | Connect over SSH as this user. |
-k | Ask 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. |
-b | Execute with elevated privileges (uses become, like sudo). |
-K | Prompt for the become password. |
ansible-playbook <playbook>.yml --checkDry run: show what would change without actually making any changes.
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.
Optionen
--diff | Show 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.
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.
Beispiel
ansible-playbook site.yml --limit "web1,web2"
ansible-playbook <playbook>.yml --stepConfirm interactively before each task runs.
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.
ansible-playbook <playbook>.yml --list-tasksList every task the playbook would run, with its tags, without running anything.Optionen
--list-tags | List the available tags instead of tasks. |
|---|---|
--list-hosts | List 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.
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.
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.
Optionen
-v | Basic extra output. |
|---|---|
-vvv | Connection and module argument detail, good for most troubleshooting. |
-vvvv | Maximum detail, including plugin loading. |
Vault
ansible-vault create secrets.ymlCreate a new file, encrypted with AES256, and open it in your editor.
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.
Optionen
--vault-id <label@source> | Use a named vault identity, so different files can be encrypted with different passwords. |
|---|---|
--ask-vault-pass | Prompt 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.
ansible-vault encrypt <file>Encrypt an existing plaintext file in place.Beispiel
ansible-vault encrypt group_vars/prod/vault.yml
ansible-vault decrypt <file>Decrypt a file in place, turning it back into plain text.
ansible-vault decrypt <file>Decrypt a file in place, turning it back into plain text.ansible-vault view <file>Print the decrypted content to the terminal without writing a plaintext file to disk.
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.
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.
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.
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.
Beispiel
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.
ansible-playbook <playbook>.yml --ask-vault-passRun a playbook that references vault-encrypted files or variables, prompting for the password.Optionen
--ask-vault-pass | Prompt 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.
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.
Beispiel
ansible-galaxy collection install community.general
ansible-galaxy collection install -r requirements.ymlInstall every collection (and optionally role) listed in a requirements.yml file.
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.
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.
ansible-galaxy role install <namespace.role>Download and install a role from Ansible Galaxy into ~/.ansible/roles by default.Beispiel
ansible-galaxy role install geerlingguy.nginx
Optionen
-p <path> | Install into a specific path instead of the default roles directory. |
|---|
ansible-galaxy role listList every role currently installed.
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).
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.
- 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.
Beispiel
- 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.
- 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.
Beispiel
- name: Create directories
ansible.builtin.file:
path: "/data/{{ item }}"
state: directory
loop:
- logs
- uploads
- cacheOptionen
loop_control.label | Control what is shown in the task output per iteration, useful when looping over large/complex dictionaries. |
|---|---|
loop_control.pause | Wait 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.
- name: <task>
<module>: ...
register: <var>Capture the result of a task (success/failure, output, return values) into a variable for use in later tasks.Beispiel
- 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.existstasks:
- 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.
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.
Beispiel
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.
- 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.
Beispiel
# nginx.conf.j2
server {
listen {{ http_port }};
server_name {{ inventory_hostname }};
}Optionen
validate "<command> %s" | Run a validation command against the rendered file before it replaces the real destination, for example "nginx -t -c %s". |
|---|---|
backup: true | Keep 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.
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).
Optionen
defaults/main.yml | Default values, easily overridden by the playbook or inventory. |
|---|---|
vars/main.yml | Role-internal variables, higher precedence, not intended for external overriding. |
meta/main.yml | Role 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.
- 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.
Die Beschreibungen in dieser Referenz sind derzeit auf Englisch.
Erklärung
Suche oder filtere nach Gruppe und kopiere einen Befehl mit einem Klick. Öffne einen Befehl für eine Erklärung, ein Beispiel und jeden Parameter, den er annimmt, mit Warnungen, wo er sich auf jeden betroffenen Host auswirkt.
🔒 Deine Eingabe bleibt in deinem Browser und wird nirgendwohin gesendet.
Häufige Fragen
Was macht --check bei ansible-playbook?
Es führt einen Testlauf aus: Ansible meldet, was es ändern würde, ohne tatsächlich etwas zu ändern. Kombiniere es mit --diff, um die inhaltlichen Unterschiede bei dateibasierten Aufgaben zu sehen.
Was ist der Unterschied zwischen einem Handler und einer normalen Aufgabe?
Ein Handler läuft nur, wenn eine andere Aufgabe ihn explizit per notify aufruft (meist um einen Dienst nach einer Konfigänderung neu zu starten oder zu laden), und läuft standardmäßig nur einmal am Ende der Play, auch wenn mehrere Aufgaben ihn aufrufen.
Wie geht es weiter?
Problem gefunden oder einen Vorschlag? Schreib uns