man ansible

Ansible Cheatsheet

The Ansible command line on one page: installing and configuring, inventories and host patterns, ad-hoc commands, ansible-playbook flags, tags, variables and facts, the playbook keywords you use most, roles and collections with ansible-galaxy, Vault, ansible-doc, debugging, connections and speed tuning, and the wider toolchain (ansible-lint, Molecule, ansible-test, ansible-navigator, ansible-builder, ansible-pull, ansible-console). Every entry has a copyable example, and most show the output you should expect.

Showing 136 of 136 commands

Install & configure

9 commands

Get Ansible on the control node, check what you are running, and see which ansible.cfg settings apply.

pipx install --include-deps ansible beginner Install the full Ansible community package (ansible-core plus the curated collections) in its own virtual environment.

Example

bash
pipx install --include-deps ansible
# Only the engine and ansible.builtin, no extra collections
pipx install ansible-core
  installed package ansible 14.0.0, installed using Python 3.12.7
  These apps are now globally available
    - ansible
    - ansible-community
    - ansible-config
    - ansible-console
    - ansible-doc
    - ansible-galaxy
    - ansible-inventory
    - ansible-playbook
    - ansible-pull
    - ansible-test
    - ansible-vault
done! ✨ 🌟 ✨

Tip: Ansible only needs to be installed on the control node. Managed Linux hosts need SSH and Python, nothing else.

python3 -m pip install --user ansible beginner Install with pip when pipx is not available; keep it in a virtual environment per project if versions differ.

Example

bash
python3 -m venv ~/.venvs/ansible
source ~/.venvs/ansible/bin/activate
python3 -m pip install ansible ansible-lint

Tip: A venv per project lets you pin ansible-core in requirements.txt so CI and laptops run the same version.

sudo dnf install ansible-core beginner Install ansible-core from the distribution repositories (AppStream on RHEL, Rocky and Alma; Fedora has the full ansible package too).

Example

bash
sudo dnf install -y ansible-core
# Debian and Ubuntu
sudo apt update && sudo apt install -y ansible

Tip: Distribution packages lag behind PyPI. Use pipx or pip when you need a recent ansible-core.

ansible --version beginner Show the ansible-core version, the config file in use, Python and Jinja versions, and where modules and collections are loaded from.

Example

bash
ansible --version
# Version of the community package (only with the full ansible package)
ansible-community --version
ansible [core 2.21.0]
  config file = /home/jeff/orbit/ansible.cfg
  configured module search path = ['/home/jeff/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/jeff/.local/share/pipx/venvs/ansible/lib/python3.12/site-packages/ansible
  ansible collection location = /home/jeff/.ansible/collections:/usr/share/ansible/collections
  executable location = /home/jeff/.local/bin/ansible
  python version = 3.12.7 (main) [GCC 11.5.0] (/home/jeff/.local/share/pipx/venvs/ansible/bin/python)
  jinja version = 3.1.6
  pyyaml version = 6.0.2 (with libyaml v0.2.5)

Tip: The "config file" line is the fastest way to answer "why is my setting ignored?": it shows which ansible.cfg won.

ansible-config init --disabled -t all > ansible.cfg intermediate Generate an ansible.cfg containing every setting, commented out, with its description and default.

Example

bash
ansible-config init --disabled -t all > ansible.cfg
grep "^;forks" ansible.cfg
;forks=5

Tip: Uncomment only what you change. A short ansible.cfg in the project root is easier to review than a full dump.

ansible.cfg (project file) beginner A minimal project ansible.cfg: default inventory, remote user, privilege escalation and a few speed settings.

Example

bash
cat > ansible.cfg <<'EOF'
[defaults]
inventory = inventory/
remote_user = deploy
forks = 20
interpreter_python = auto_silent

[privilege_escalation]
become = true
become_method = sudo

[ssh_connection]
pipelining = true
EOF
ansible-config dump --only-changed

Tip: Search order: ANSIBLE_CONFIG, ./ansible.cfg, ~/.ansible.cfg, /etc/ansible/ansible.cfg. Only the first one found is used, settings are not merged. Ansible ignores ./ansible.cfg in a world-writable directory.

ansible-config dump --only-changed intermediate List only the settings that differ from the defaults, and where each value came from.

Example

bash
ansible-config dump --only-changed
# Include plugin settings such as callbacks and connections
ansible-config dump --only-changed -t all
CONFIG_FILE() = /home/jeff/orbit/ansible.cfg
DEFAULT_BECOME(/home/jeff/orbit/ansible.cfg) = True
DEFAULT_FORKS(/home/jeff/orbit/ansible.cfg) = 20
DEFAULT_HOST_LIST(/home/jeff/orbit/ansible.cfg) = ['/home/jeff/orbit/inventory']
DEFAULT_REMOTE_USER(/home/jeff/orbit/ansible.cfg) = deploy

Tip: Paste this output into bug reports and pull requests: it shows the effective configuration in a few lines.

ansible-config list intermediate Describe every setting: its ini key, environment variable, default and accepted values.

Example

bash
ansible-config list | grep -A8 '^DEFAULT_FORKS'
# Show the current config file as it is
ansible-config view
DEFAULT_FORKS:
  default: 5
  description: Maximum number of forks Ansible will use to execute tasks on target
    hosts.
  env:
  - name: ANSIBLE_FORKS
  ini:
  - key: forks
    section: defaults

Tip: Every ini setting has an ANSIBLE_* environment variable, which is handy for one-off overrides in CI.

ssh-copy-id deploy@<host> beginner Put your public key on a managed node so Ansible can log in without a password.

Example

bash
ssh-keygen -t ed25519 -C "ansible@orbit"
ssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@web01.orbit.internal
ansible web01 -m ansible.builtin.ping

Tip: Connect once by hand (or set host_key_checking deliberately) so the host key is in known_hosts before the first run.

Inventory & host patterns

11 commands

Describe your hosts and groups, inspect what Ansible sees, and pick exactly the hosts a command runs on.

inventory in INI format beginner Group hosts in a simple INI file, with host variables inline and group variables in a [group:vars] block.

Example

bash
mkdir -p inventory
cat > inventory/hosts.ini <<'EOF'
[web]
web01.orbit.internal
web02.orbit.internal ansible_port=2222

[db]
db01.orbit.internal ansible_host=10.0.2.15

[prod:children]
web
db

[web:vars]
http_port=8080
EOF
ansible-inventory -i inventory/hosts.ini --graph

Tip: Every host is also in the implicit groups all and ungrouped (when it belongs to no other group).

inventory in YAML format beginner The same inventory in YAML, which is easier to nest and to generate from other tools.

Example

bash
cat > inventory/hosts.yml <<'EOF'
all:
  children:
    web:
      hosts:
        web01.orbit.internal:
        web02.orbit.internal:
          ansible_port: 2222
      vars:
        http_port: 8080
    db:
      hosts:
        db01.orbit.internal:
          ansible_host: 10.0.2.15
EOF
ansible-inventory -i inventory/hosts.yml --list -y
host ranges web[01:10] beginner Declare many similarly named hosts with a numeric or alphabetic range instead of listing each one.

Example

bash
cat > inventory/hosts.ini <<'EOF'
[web]
web[01:10].orbit.internal

[db]
db-[a:c].orbit.internal
EOF
ansible web --list-hosts | head -4
  hosts (10):
    web01.orbit.internal
    web02.orbit.internal
    web03.orbit.internal
group_vars/ and host_vars/ intermediate Keep variables in files next to the inventory: one file (or directory) per group or host.

Example

bash
mkdir -p inventory/group_vars inventory/host_vars
echo "ntp_server: time.orbit.internal" > inventory/group_vars/all.yml
echo "nginx_workers: 4" > inventory/group_vars/web.yml
echo "nginx_workers: 8" > inventory/host_vars/web01.orbit.internal.yml
ansible-inventory --host web01.orbit.internal
{
    "nginx_workers": 8,
    "ntp_server": "time.orbit.internal"
}

Tip: Host vars override group vars, and child groups override parent groups. group_vars next to the playbook are loaded too.

ansible-inventory --graph beginner Draw the group tree, optionally for a single group and with the variables of each host.

Example

bash
ansible-inventory --graph
ansible-inventory --graph web --vars
@all:
  |--@ungrouped:
  |--@prod:
  |  |--@web:
  |  |  |--web01.orbit.internal
  |  |  |--web02.orbit.internal
  |  |--@db:
  |  |  |--db01.orbit.internal

Tip: Run it after every inventory change: a host that lands in the wrong group shows up immediately.

ansible-inventory --list intermediate Print the whole parsed inventory, groups, hosts and merged variables, as JSON or YAML.

Example

bash
ansible-inventory --list -y
# Save it, e.g. to diff two versions of a dynamic inventory
ansible-inventory --list --output /tmp/inventory.json
all:
  children:
    prod:
      children:
        db:
          hosts:
            db01.orbit.internal:
              ansible_host: 10.0.2.15
              ntp_server: time.orbit.internal
ansible-inventory --host <host> intermediate Show the variables Ansible resolved for one host from every inventory source.

Example

bash
ansible-inventory --host web02.orbit.internal -y
ansible_port: 2222
http_port: 8080
nginx_workers: 4
ntp_server: time.orbit.internal

Tip: Inventory variables only: facts, play vars and -e extra vars are applied later, at run time.

ansible <pattern> --list-hosts beginner Preview which hosts a pattern matches, without connecting to anything.

Example

bash
ansible all --list-hosts
ansible 'web:db' --list-hosts
  hosts (3):
    web01.orbit.internal
    web02.orbit.internal
    db01.orbit.internal
patterns: web:db web:&prod web:!web02 intermediate Combine groups: a colon is a union, :& an intersection and :! an exclusion. The same syntax works in --limit and in hosts:.

Example

bash
# web OR db
ansible 'web:db' -m ansible.builtin.ping
# web hosts that are also in prod
ansible 'web:&prod' -m ansible.builtin.ping
# all web hosts except web02
ansible 'web:!web02.orbit.internal' -m ansible.builtin.ping
# regular expression and index
ansible '~web0[12]\.orbit' --list-hosts
ansible 'web[0]' --list-hosts

Tip: Always quote patterns: ! and & mean something to the shell.

-i host1,host2, beginner Pass hosts directly on the command line as a comma-separated list; the trailing comma tells Ansible it is a list, not a file.

Example

bash
ansible all -i 'web01.orbit.internal,web02.orbit.internal,' -m ansible.builtin.ping
ansible-playbook -i localhost, -c local site.yml

Tip: Great for a quick test against one new server before it is added to the real inventory.

dynamic inventory: amazon.aws.aws_ec2 advanced Build the inventory from cloud APIs with an inventory plugin; the file name must end in aws_ec2.yml (or .yaml).

Example

bash
ansible-galaxy collection install amazon.aws
cat > inventory/orbit.aws_ec2.yml <<'EOF'
plugin: amazon.aws.aws_ec2
regions:
  - us-east-1
filters:
  tag:Project: orbit
  instance-state-name: running
keyed_groups:
  - key: tags.Role
    prefix: role
hostnames:
  - private-ip-address
EOF
ansible-inventory -i inventory/orbit.aws_ec2.yml --graph
@all:
  |--@ungrouped:
  |--@aws_ec2:
  |  |--10.0.1.21
  |  |--10.0.1.22
  |--@role_web:
  |  |--10.0.1.21
  |  |--10.0.1.22

Tip: Pass a directory to -i and Ansible merges static files and plugin configs, so group_vars still apply to cloud hosts.

Ad-hoc commands

15 commands

One-off tasks with /usr/bin/ansible: check reachability, run a command everywhere, or fix one thing fast without writing a playbook.

ansible all -m ansible.builtin.ping beginner Check that Ansible can log in to every host and run Python there. This is not an ICMP ping.

Example

bash
ansible all -m ansible.builtin.ping
web01.orbit.internal | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
db01.orbit.internal | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: ssh: connect to host 10.0.2.15 port 22: Connection timed out",
    "unreachable": true
}

Tip: UNREACHABLE means SSH failed; FAILED means Ansible connected but the module failed (often missing Python).

ansible <pattern> -a "<command>" beginner Run a command on the hosts with the default command module (no shell, so no pipes, redirects or variables).

Example

bash
ansible web -a "uptime"
# One line per host, good for grep
ansible web -a "uptime" -o
web01.orbit.internal | CHANGED | rc=0 >>
 10:02:11 up 12 days,  3:41,  1 user,  load average: 0.08, 0.03, 0.01
web02.orbit.internal | CHANGED | rc=0 >>
 10:02:11 up 12 days,  3:40,  0 users,  load average: 0.00, 0.01, 0.00

Tip: command always reports CHANGED because Ansible cannot know what an arbitrary command did.

ansible <pattern> -m ansible.builtin.shell -a "..." beginner Run through /bin/sh on the remote host when you need pipes, redirection, globbing or environment variables.

Example

bash
ansible web -m ansible.builtin.shell -a "df -h / | tail -1"
ansible db -m ansible.builtin.shell -a 'echo $HOSTNAME'
web01.orbit.internal | CHANGED | rc=0 >>
/dev/sda1        40G   13G   28G  32% /
web02.orbit.internal | CHANGED | rc=0 >>
/dev/sda1        40G   21G   20G  52% /

Tip: Use single quotes around the -a value when it contains $ so your local shell does not expand it first.

-b / --become beginner Run the module as root (or as --become-user) with sudo; add -K when sudo asks for a password.

Example

bash
ansible web -b -a "whoami" -o
ansible web -b -K -a "systemctl restart nginx"
ansible db -b --become-user postgres -a "psql -c 'select version()'"

Tip: -k (lowercase) asks for the SSH password, -K (uppercase) for the sudo password.

ansible <pattern> -m ansible.builtin.package beginner Install, remove or update packages with the OS package manager (dnf, apt, zypper...) picked automatically.

Example

bash
ansible web -b -m ansible.builtin.package -a "name=nginx state=present"
# Distribution-specific modules expose more options
ansible web -b -m ansible.builtin.dnf -a "name=* state=latest security=true"
ansible web -b -m ansible.builtin.apt -a "update_cache=true upgrade=dist"
web01.orbit.internal | CHANGED => {
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Installed: nginx-1:1.20.1-22.el9.x86_64"
    ]
}
ansible <pattern> -m ansible.builtin.service beginner Start, stop, restart or enable services.

Example

bash
ansible web -b -m ansible.builtin.service -a "name=nginx state=restarted"
ansible web -b -m ansible.builtin.systemd_service -a "name=nginx enabled=true state=started daemon_reload=true"

Tip: Run it twice: the second run reports SUCCESS with changed false. That idempotence is the whole point of modules.

ansible <pattern> -m ansible.builtin.copy beginner Push a file (or inline content) to the hosts with owner and permissions.

Example

bash
ansible web -b -m ansible.builtin.copy -a "src=./files/motd dest=/etc/motd owner=root mode=0644"
ansible web -b -m ansible.builtin.copy -a "content='maintenance tonight 22:00\n' dest=/etc/motd"
ansible <pattern> -m ansible.builtin.file beginner Create directories, symlinks or empty files, change permissions, or delete paths.

Example

bash
ansible web -b -m ansible.builtin.file -a "path=/srv/orbit state=directory owner=orbit mode=0755"
ansible web -b -m ansible.builtin.file -a "src=/srv/orbit/releases/42 dest=/srv/orbit/current state=link"
ansible web -b -m ansible.builtin.file -a "path=/tmp/orbit-build state=absent"
ansible <pattern> -m ansible.builtin.fetch intermediate Copy files from the managed nodes back to the control node, one subdirectory per host.

Example

bash
ansible web -b -m ansible.builtin.fetch -a "src=/var/log/nginx/error.log dest=./logs/"
find logs -type f
logs/web01.orbit.internal/var/log/nginx/error.log
logs/web02.orbit.internal/var/log/nginx/error.log

Tip: Add flat=true only when fetching from a single host, otherwise every host overwrites the same file.

ansible <pattern> -m ansible.builtin.user intermediate Manage local users and their groups.

Example

bash
ansible all -b -m ansible.builtin.user -a "name=deploy groups=wheel append=true shell=/bin/bash"
ansible all -b -m ansible.builtin.user -a "name=olduser state=absent remove=true"

Tip: append=true adds the groups; without it the user is removed from every group not listed.

ansible <pattern> -m ansible.builtin.reboot intermediate Reboot hosts and wait until they are back and accept SSH again.

Example

bash
ansible web -b -m ansible.builtin.reboot -a "reboot_timeout=600" -f 1
web01.orbit.internal | CHANGED => {
    "changed": true,
    "elapsed": 47,
    "rebooted": true
}

Tip: -f 1 reboots one host at a time so the web group never goes down all at once.

ansible <pattern> -m ansible.builtin.setup beginner Gather facts (OS, network, CPU, memory, disks) and filter them by name.

Example

bash
ansible web01.orbit.internal -m ansible.builtin.setup -a "filter=ansible_distribution*"
ansible web -m ansible.builtin.setup -a "gather_subset=!all,network"
web01.orbit.internal | SUCCESS => {
    "ansible_facts": {
        "ansible_distribution": "Rocky",
        "ansible_distribution_file_variety": "RedHat",
        "ansible_distribution_major_version": "9",
        "ansible_distribution_release": "Blue Onyx",
        "ansible_distribution_version": "9.7"
    },
    "changed": false
}
-f / --forks <n> intermediate Change how many hosts Ansible works on in parallel (default 5).

Example

bash
ansible all -f 50 -a "needs-restarting -r" -b
# Strictly one host at a time
ansible web -f 1 -b -a "systemctl restart orbit-api"

Tip: Raise forks for big fleets; the limit is control-node CPU, memory and SSH connections, not the managed hosts.

-B <seconds> -P <poll> (async) advanced Run a long command in the background on each host; with -P 0 Ansible returns immediately and you check the job later.

Example

bash
ansible db -b -B 3600 -P 0 -a "/usr/local/bin/orbit-backup --full"
# Use the ansible_job_id printed above
ansible db -b -m ansible.builtin.async_status -a "jid=j123456789.4242"
db01.orbit.internal | SUCCESS => {
    "ansible_job_id": "j123456789.4242",
    "finished": 0,
    "started": 1
}

Tip: Background jobs survive an SSH disconnect, which makes them safe for work that outlasts your laptop's session.

ansible <pattern> -C -D -m ... intermediate Ad-hoc check mode with diff: see what a module would change without changing it.

Example

bash
ansible web -b -C -D -m ansible.builtin.lineinfile -a "path=/etc/ssh/sshd_config regexp='^#?PermitRootLogin' line='PermitRootLogin no'"
--- before: /etc/ssh/sshd_config (content)
+++ after: /etc/ssh/sshd_config (content)
@@ -38,7 +38,7 @@
-#PermitRootLogin prohibit-password
+PermitRootLogin no

web01.orbit.internal | CHANGED => {
    "changed": true,
    "msg": "line replaced"
}

Running playbooks

13 commands

ansible-playbook flags you reach for every day: dry runs, limiting hosts, passing variables, and listing what a run would do.

ansible-playbook <playbook.yml> beginner Run every play in the playbook against the hosts each play targets.

Example

bash
ansible-playbook -i inventory/ site.yml
PLAY [Configure web servers] ***************************************************

TASK [Gathering Facts] *********************************************************
ok: [web01.orbit.internal]
ok: [web02.orbit.internal]

TASK [Install nginx] ***********************************************************
changed: [web01.orbit.internal]
ok: [web02.orbit.internal]

PLAY RECAP *********************************************************************
web01.orbit.internal       : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web02.orbit.internal       : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Tip: The exit code is non-zero when any host failed or was unreachable, so CI fails without parsing the recap.

ansible-playbook --syntax-check beginner Parse the playbook and the roles and files it imports without connecting to any host.

Example

bash
ansible-playbook site.yml --syntax-check
playbook: site.yml

Tip: It does not catch everything (dynamic includes and templates are evaluated at run time); pair it with ansible-lint.

ansible-playbook --check --diff beginner Dry run: report what would change and show the file diffs, without changing anything.

Example

bash
ansible-playbook site.yml --check --diff
ansible-playbook site.yml -C -D -l web01.orbit.internal
TASK [Render nginx config] *****************************************************
--- before: /etc/nginx/conf.d/orbit.conf
+++ after: /home/jeff/.ansible/tmp/ansible-local-1842x/tmp3k9d/orbit.conf.j2
@@ -1,4 +1,4 @@
 server {
-    listen 80;
+    listen 8080;
     server_name orbit.example.com;
changed: [web01.orbit.internal]

Tip: Tasks that use command or shell are skipped in check mode; add check_mode: false to read-only commands whose results later tasks need.

-l / --limit <pattern> beginner Run the playbook on a subset of its hosts. Accepts the same patterns as ad-hoc commands, or @file with one host per line.

Example

bash
ansible-playbook site.yml -l web01.orbit.internal
ansible-playbook site.yml --limit 'web:!web02.orbit.internal'
ansible-playbook site.yml --limit @failed-hosts.txt

Tip: Do a canary run with --limit on one host, read the recap, then run the rest.

-e / --extra-vars beginner Pass variables on the command line as key=value, JSON, or @file. Extra vars have the highest precedence of all.

Example

bash
ansible-playbook deploy.yml -e "release=2.4.1 env=staging"
ansible-playbook deploy.yml -e '{"replicas": 3, "features": ["search", "export"]}'
ansible-playbook deploy.yml -e @vars/prod.yml

Tip: key=value always gives strings; use JSON when you need numbers, booleans or lists.

--list-hosts beginner Show which hosts each play would run on, after --limit is applied.

Example

bash
ansible-playbook site.yml --list-hosts -l web
playbook: site.yml

  play #1 (web): Configure web servers	TAGS: []
    pattern: ['web']
    hosts (2):
      web01.orbit.internal
      web02.orbit.internal

  play #2 (db): Configure databases	TAGS: []
    pattern: ['db']
    hosts (0):
--list-tasks intermediate Print every task each play would run, with its tags, without executing anything.

Example

bash
ansible-playbook site.yml --list-tasks
ansible-playbook site.yml --list-tasks --tags nginx
playbook: site.yml

  play #1 (web): Configure web servers	TAGS: []
    tasks:
      nginx : Install nginx	TAGS: [nginx, packages]
      nginx : Render nginx config	TAGS: [config, nginx]
      orbit : Deploy release	TAGS: [deploy]
--start-at-task "<name>" intermediate Skip everything before the named task, for resuming a long playbook after you fixed a failure.

Example

bash
ansible-playbook site.yml --start-at-task "Deploy release" -l web02.orbit.internal

Tip: Tasks before the start point are skipped, so facts and variables they would have registered are missing.

--step intermediate Ask for confirmation before each task: answer y to run it, n to skip it, c to stop asking.

Example

bash
ansible-playbook site.yml --step -l web01.orbit.internal
Perform task: TASK: nginx : Install nginx (N)o/(y)es/(c)ontinue:
-K / -k / -u <user> beginner Prompt for the sudo password (-K), the SSH password (-k), or connect as another remote user (-u).

Example

bash
ansible-playbook site.yml -u admin -K
ansible-playbook bootstrap.yml -u root -k

Tip: A bootstrap playbook run once with -u root -k can create the deploy user and its key; afterwards you never need passwords.

--force-handlers intermediate Run notified handlers even when a later task fails, so a changed config still gets its restart.

Example

bash
ansible-playbook site.yml --force-handlers

Tip: Set force_handlers: true on the play to make this the default for that play.

--flush-cache intermediate Clear the fact cache for the targeted hosts before the run, so no stale facts are used.

Example

bash
ansible-playbook site.yml --flush-cache
-v / -vv / -vvv / -vvvv beginner Increase output detail: -v shows task results, -vvv the connection details, -vvvv also SSH debugging and plugin loading.

Example

bash
ansible-playbook site.yml -v
ansible-playbook site.yml -l web01.orbit.internal -vvvv 2>&1 | tee run.log

Tip: Start with -v. Jump to -vvvv only for connection and become problems; it is very noisy.

Tags

6 commands

Run or skip parts of a playbook by tag, and the special tags that change the defaults.

tags: [...] beginner Label tasks, blocks, roles or whole plays so they can be selected from the command line.

Example

bash
cat > site.yml <<'EOF'
- name: Configure web servers
  hosts: web
  roles:
    - role: nginx
      tags: [nginx]
  tasks:
    - name: Deploy release
      ansible.builtin.unarchive:
        src: "dist/orbit-{{ release }}.tar.gz"
        dest: /srv/orbit/releases/
      tags: [deploy]
EOF
ansible-playbook site.yml --list-tags
playbook: site.yml

  play #1 (web): Configure web servers	TAGS: []
      TASK TAGS: [deploy, nginx]

Tip: Tags on a role, block or import are inherited by every task inside it.

-t / --tags <tags> beginner Run only the tasks with these tags.

Example

bash
ansible-playbook site.yml --tags deploy
ansible-playbook site.yml -t nginx,config
--skip-tags <tags> beginner Run everything except the tasks with these tags.

Example

bash
ansible-playbook site.yml --skip-tags packages

Tip: Skipping slow package tasks during a config-only change can cut minutes from a run.

--list-tags beginner Show every tag available in the playbook without running it.

Example

bash
ansible-playbook site.yml --list-tags
tags: [always] / tags: [never] intermediate always runs a task unless it is explicitly skipped; never skips a task unless one of its tags is requested.

Example

bash
cat > maintenance.yml <<'EOF'
- hosts: web
  tasks:
    - name: Load secrets
      ansible.builtin.include_vars: vault.yml
      tags: [always]
    - name: Drop the cache
      ansible.builtin.file:
        path: /var/cache/orbit
        state: absent
      tags: [never, purge]
EOF
ansible-playbook maintenance.yml --tags purge
--tags tagged / untagged / all intermediate Special values: tagged runs only tagged tasks, untagged only tasks without tags, all (the default) runs everything.

Example

bash
ansible-playbook site.yml --tags untagged
ansible-playbook site.yml --skip-tags tagged

Variables & facts

10 commands

Where variables come from, how to inspect them, and how to use facts gathered from the hosts.

ansible localhost -m ansible.builtin.debug -a "msg=..." beginner Try out a Jinja2 expression or filter on the control node before you put it in a playbook.

Example

bash
ansible localhost -m ansible.builtin.debug -a "msg={{ '2.4.1' is version('2.4.0', '>') }}"
ansible localhost -m ansible.builtin.debug -a "msg={{ ['b','a','b'] | unique | sort }}"
ansible localhost -e "release=2.4.1" -m ansible.builtin.debug -a "msg=orbit-{{ release }}.tar.gz"
localhost | SUCCESS => {
    "msg": true
}
ansible <host> -m ansible.builtin.debug -a "var=..." beginner Print a variable as Ansible resolves it for a host, including inventory vars and magic variables.

Example

bash
ansible web01.orbit.internal -m ansible.builtin.debug -a "var=nginx_workers"
ansible web01.orbit.internal -m ansible.builtin.debug -a "var=groups"
web01.orbit.internal | SUCCESS => {
    "nginx_workers": 8
}
variable precedence (short version) intermediate From lowest to highest: role defaults, inventory group_vars, inventory host_vars, play vars, role vars, task vars, set_fact/registered vars, and extra vars (-e) on top.

Example

bash
# Role default
echo "nginx_workers: 2" > roles/nginx/defaults/main.yml
# Inventory host var wins over the default
echo "nginx_workers: 8" > inventory/host_vars/web01.orbit.internal.yml
# Extra vars win over everything
ansible-playbook site.yml -e nginx_workers=16

Tip: Put tunable values in role defaults/main.yml so inventories can override them; keep role vars/main.yml for constants.

register: + debug beginner Save the result of a task in a variable and inspect its fields (rc, stdout, stdout_lines, changed...).

Example

bash
cat > check.yml <<'EOF'
- hosts: web
  tasks:
    - name: Read the running release
      ansible.builtin.command: readlink /srv/orbit/current
      register: current
      changed_when: false
    - name: Show it
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} runs {{ current.stdout | basename }}"
EOF
ansible-playbook check.yml
TASK [Show it] *****************************************************************
ok: [web01.orbit.internal] => {
    "msg": "web01.orbit.internal runs 42"
}

Tip: changed_when: false keeps read-only commands from showing as changed in every run.

ansible_facts['...'] beginner Use gathered facts in tasks and templates; the ansible_facts dictionary is the preferred way to read them.

Example

bash
cat > facts.yml <<'EOF'
- hosts: all
  tasks:
    - ansible.builtin.debug:
        msg: >-
          {{ ansible_facts['hostname'] }} runs
          {{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }}
          with {{ ansible_facts['memtotal_mb'] }} MB RAM
EOF
ansible-playbook facts.yml
ok: [web01.orbit.internal] => {
    "msg": "web01 runs Rocky 9.7 with 3653 MB RAM"
}
gather_facts: false / gather_subset intermediate Skip fact gathering when a play does not need facts, or collect only the subsets you use.

Example

bash
cat > quick.yml <<'EOF'
- hosts: web
  gather_facts: false
  tasks:
    - ansible.builtin.setup:
        gather_subset: [network]
    - ansible.builtin.debug:
        var: ansible_facts['default_ipv4']['address']
EOF
ansible-playbook quick.yml

Tip: Fact gathering is often the slowest step on big fleets; turning it off where it is not needed is free speed.

set_fact intermediate Compute a variable during the run; it lives for that host for the rest of the playbook.

Example

bash
cat > release.yml <<'EOF'
- hosts: web
  tasks:
    - ansible.builtin.set_fact:
        release_dir: "/srv/orbit/releases/{{ release }}"
        is_canary: "{{ inventory_hostname == groups['web'][0] }}"
    - ansible.builtin.debug:
        msg: "{{ release_dir }} canary={{ is_canary }}"
EOF
ansible-playbook release.yml -e release=43
magic variables: inventory_hostname, groups, hostvars intermediate Built-in variables about the inventory and the run: the current host, group membership, and every host's variables.

Example

bash
cat > hosts-file.yml <<'EOF'
- hosts: web
  tasks:
    - name: Point web servers at the database
      ansible.builtin.lineinfile:
        path: /etc/hosts
        line: "{{ hostvars['db01.orbit.internal']['ansible_host'] }} db.orbit"
      become: true
    - ansible.builtin.debug:
        msg: "{{ inventory_hostname }} is one of {{ groups['web'] | length }} web hosts"
EOF
ansible-playbook hosts-file.yml

Tip: Facts of another host in hostvars only exist if facts were gathered for it earlier in the same run (or are cached).

vars_files / include_vars intermediate Load variables from YAML files, statically at play start (vars_files) or dynamically in a task (include_vars).

Example

bash
cat > env.yml <<'EOF'
- hosts: web
  vars_files:
    - vars/common.yml
  tasks:
    - ansible.builtin.include_vars: "vars/{{ env }}.yml"
    - ansible.builtin.debug:
        var: api_url
EOF
ansible-playbook env.yml -e env=staging
/etc/ansible/facts.d/*.fact (local facts) advanced Let hosts publish their own facts: JSON or INI files (or executables printing JSON) in facts.d appear under ansible_local.

Example

bash
ansible web -b -m ansible.builtin.copy -a "dest=/etc/ansible/facts.d/orbit.fact content='{\"release\": \"42\", \"tier\": \"blue\"}' mode=0644"
ansible web -m ansible.builtin.setup -a "filter=ansible_local"
web01.orbit.internal | SUCCESS => {
    "ansible_facts": {
        "ansible_local": {
            "orbit": {
                "release": "42",
                "tier": "blue"
            }
        }
    },
    "changed": false
}

Playbook building blocks

12 commands

The keywords most playbooks are made of, each as a small runnable example: handlers, loops, conditions, error handling, templates and rolling updates.

play skeleton: hosts / become / tasks beginner A complete minimal playbook: which hosts, how to escalate, and an ordered list of tasks using fully qualified module names.

Example

bash
cat > site.yml <<'EOF'
- name: Configure web servers
  hosts: web
  become: true
  tasks:
    - name: Install nginx
      ansible.builtin.package:
        name: nginx
        state: present
    - name: Start and enable nginx
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true
EOF
ansible-playbook site.yml

Tip: Give every task a name: it is what you read in the output and what --start-at-task matches.

notify: + handlers: beginner Run a task (for example a restart) only when another task changed something, once at the end of the play.

Example

bash
cat > nginx.yml <<'EOF'
- hosts: web
  become: true
  tasks:
    - name: Render nginx config
      ansible.builtin.template:
        src: templates/orbit.conf.j2
        dest: /etc/nginx/conf.d/orbit.conf
        validate: nginx -t -c %s
      notify: Reload nginx
  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded
EOF
ansible-playbook nginx.yml
TASK [Render nginx config] *****************************************************
changed: [web01.orbit.internal]

RUNNING HANDLER [Reload nginx] *************************************************
changed: [web01.orbit.internal]

Tip: Use ansible.builtin.meta: flush_handlers when a handler must run before the next task, not at the end of the play.

ansible.builtin.template + Jinja2 beginner Render a Jinja2 template with variables and facts into a file on the host.

Example

bash
mkdir -p templates
cat > templates/orbit.conf.j2 <<'EOF'
# {{ ansible_managed }}
upstream orbit_api {
{% for host in groups['web'] %}
    server {{ hostvars[host]['ansible_host'] | default(host) }}:{{ http_port }};
{% endfor %}
}
server {
    listen 80;
    server_name {{ server_name | default('orbit.example.com') }};
    location / { proxy_pass http://orbit_api; }
}
EOF
ansible-playbook nginx.yml --check --diff

Tip: The validate option runs a check on the rendered temp file before it replaces the real one, so a broken config never lands.

loop: beginner Repeat a task for each item in a list; the current element is item.

Example

bash
cat > users.yml <<'EOF'
- hosts: all
  become: true
  tasks:
    - name: Create team accounts
      ansible.builtin.user:
        name: "{{ item.name }}"
        groups: "{{ item.groups }}"
        append: true
      loop:
        - { name: ana, groups: wheel }
        - { name: bruno, groups: orbit }
      loop_control:
        label: "{{ item.name }}"
EOF
ansible-playbook users.yml
TASK [Create team accounts] ****************************************************
changed: [web01.orbit.internal] => (item=ana)
changed: [web01.orbit.internal] => (item=bruno)

Tip: Many package modules accept a list in name:, which is one transaction and much faster than looping.

when: beginner Run a task only when a condition is true; conditions are raw Jinja2 expressions without {{ }}.

Example

bash
cat > os.yml <<'EOF'
- hosts: all
  become: true
  tasks:
    - name: Install EPEL on Rocky
      ansible.builtin.dnf:
        name: epel-release
      when: ansible_facts['distribution'] == 'Rocky'
    - name: Only on big machines
      ansible.builtin.debug:
        msg: "plenty of RAM"
      when:
        - ansible_facts['memtotal_mb'] > 8000
        - "'web' in group_names"
EOF
ansible-playbook os.yml

Tip: A list under when: means all conditions must be true. Recent ansible-core releases are stricter: a condition must evaluate to a boolean, so write my_var | bool for string flags.

block: / rescue: / always: intermediate Group tasks, run recovery tasks when one fails, and run cleanup tasks no matter what.

Example

bash
cat > deploy.yml <<'EOF'
- hosts: web
  become: true
  serial: 1
  tasks:
    - block:
        - name: Switch to the new release
          ansible.builtin.file:
            src: "/srv/orbit/releases/{{ release }}"
            dest: /srv/orbit/current
            state: link
        - name: Health check
          ansible.builtin.uri:
            url: http://localhost:8080/health
            status_code: 200
      rescue:
        - name: Roll back
          ansible.builtin.file:
            src: "/srv/orbit/releases/{{ previous_release }}"
            dest: /srv/orbit/current
            state: link
      always:
        - name: Restart the API
          ansible.builtin.service:
            name: orbit-api
            state: restarted
EOF
ansible-playbook deploy.yml -e "release=43 previous_release=42"

Tip: If rescue succeeds the host counts as rescued in the recap, not failed, and the play continues.

changed_when: / failed_when: / ignore_errors: intermediate Decide yourself what counts as changed or failed for a task, or let a failure pass.

Example

bash
cat > migrate.yml <<'EOF'
- hosts: db
  tasks:
    - name: Run migrations
      ansible.builtin.command: /srv/orbit/bin/migrate up
      register: migrate
      changed_when: "'No migrations' not in migrate.stdout"
      failed_when: migrate.rc not in [0, 3]
    - name: Optional cleanup
      ansible.builtin.command: /srv/orbit/bin/cleanup-tmp
      ignore_errors: true
EOF
ansible-playbook migrate.yml

Tip: Prefer failed_when with a precise condition over ignore_errors, which hides real problems too.

serial: / max_fail_percentage: intermediate Rolling updates: run the play on a few hosts at a time and stop if too many fail.

Example

bash
cat > rolling.yml <<'EOF'
- hosts: web
  become: true
  serial: [1, "25%", "100%"]
  max_fail_percentage: 0
  tasks:
    - name: Upgrade the API package
      ansible.builtin.dnf:
        name: orbit-api
        state: latest
      notify: Restart API
  handlers:
    - name: Restart API
      ansible.builtin.service:
        name: orbit-api
        state: restarted
EOF
ansible-playbook rolling.yml

Tip: serial: [1, "25%", "100%"] is a canary pattern: one host first, then a quarter, then the rest.

delegate_to: / run_once: advanced Run a task on a different host (for example a load balancer) on behalf of the current one, or only once per play.

Example

bash
cat > drain.yml <<'EOF'
- hosts: web
  serial: 1
  tasks:
    - name: Take the host out of the load balancer
      ansible.builtin.command: "/usr/local/bin/lb-drain {{ inventory_hostname }}"
      delegate_to: lb01.orbit.internal
    - name: Notify chat once
      ansible.builtin.uri:
        url: https://chat.example.com/hooks/deploy
        method: POST
        body_format: json
        body: { text: "Deploying {{ release }}" }
      run_once: true
      delegate_to: localhost
EOF
ansible-playbook drain.yml -e release=43
import_tasks vs include_tasks intermediate import_* is static (resolved before the run, tags and --list-tasks see inside); include_* is dynamic (resolved at run time, can use loops and runtime variables).

Example

bash
cat > site.yml <<'EOF'
- hosts: web
  tasks:
    - ansible.builtin.import_tasks: tasks/common.yml
    - ansible.builtin.include_tasks: "tasks/{{ ansible_facts['os_family'] | lower }}.yml"
- ansible.builtin.import_playbook: db.yml
EOF
ansible-playbook site.yml --list-tasks

Tip: Tags on an include_tasks apply only to the include itself; use apply: { tags: [...] } or import_tasks when you need them inherited.

async: / poll: (in a playbook) advanced Start a long task, continue with other work, and wait for it later with async_status.

Example

bash
cat > backup.yml <<'EOF'
- hosts: db
  become: true
  tasks:
    - name: Start the backup
      ansible.builtin.command: /usr/local/bin/orbit-backup --full
      async: 3600
      poll: 0
      register: backup_job
    - name: Wait for it
      ansible.builtin.async_status:
        jid: "{{ backup_job.ansible_job_id }}"
      register: job
      until: job.finished
      retries: 120
      delay: 30
EOF
ansible-playbook backup.yml
until: / retries: / delay: intermediate Retry a task until a condition is true, for example until a service answers after a restart.

Example

bash
cat > wait.yml <<'EOF'
- hosts: web
  tasks:
    - name: Wait for the API
      ansible.builtin.uri:
        url: http://localhost:8080/health
      register: health
      until: health.status == 200
      retries: 10
      delay: 5
EOF
ansible-playbook wait.yml
FAILED - RETRYING: [web01.orbit.internal]: Wait for the API (10 retries left).
ok: [web01.orbit.internal]

Roles & collections (ansible-galaxy)

12 commands

Create, install, list and publish roles and collections with ansible-galaxy.

ansible-galaxy role init <name> beginner Create a role skeleton with tasks, handlers, defaults, vars, templates, files and meta directories.

Example

bash
ansible-galaxy role init --init-path roles nginx
find roles/nginx -maxdepth 2 -name main.yml
- Role nginx was created successfully
roles/nginx/defaults/main.yml
roles/nginx/handlers/main.yml
roles/nginx/meta/main.yml
roles/nginx/tasks/main.yml
roles/nginx/tests/test.yml
roles/nginx/vars/main.yml
roles: / ansible.builtin.import_role beginner Use roles from a play, either in the roles: list or as a task when you need ordering, conditions or loops.

Example

bash
cat > site.yml <<'EOF'
- hosts: web
  become: true
  roles:
    - nginx
    - role: orbit
      vars:
        orbit_release: "43"
  tasks:
    - name: Monitoring only in prod
      ansible.builtin.include_role:
        name: node_exporter
      when: env == 'prod'
EOF
ansible-playbook site.yml -e env=prod
ansible-galaxy collection install <namespace.name> beginner Install a collection from Ansible Galaxy, optionally pinned to a version range.

Example

bash
ansible-galaxy collection install community.general
ansible-galaxy collection install 'ansible.posix:>=2.0.0,<3.0.0'
# Into the project instead of ~/.ansible/collections
ansible-galaxy collection install community.docker -p ./collections
Starting galaxy collection install process
Process install dependency map
Starting collection install process
Installing 'ansible.posix:2.1.0' to '/home/jeff/.ansible/collections/ansible_collections/ansible/posix'
ansible.posix:2.1.0 was installed successfully

Tip: An installed version is not replaced unless you add --upgrade (-U) or --force.

ansible-galaxy install -r requirements.yml beginner Install every role and collection the project needs from one pinned requirements file.

Example

bash
cat > requirements.yml <<'EOF'
collections:
  - name: community.general
    version: ">=11.0.0"
  - name: amazon.aws
  - name: https://github.com/orbit/ansible-collection-platform.git
    type: git
    version: main
roles:
  - name: geerlingguy.docker
    version: 7.4.1
EOF
ansible-galaxy install -r requirements.yml

Tip: Commit requirements.yml and run this in CI. Use ansible-galaxy collection install -r ... --upgrade to move to newer allowed versions.

ansible-galaxy collection list beginner List installed collections and versions, grouped by install path.

Example

bash
ansible-galaxy collection list
ansible-galaxy collection list community.general
# /home/jeff/.ansible/collections/ansible_collections
Collection        Version
----------------- -------
amazon.aws        10.1.0
ansible.posix     2.1.0
community.general 11.4.0

Tip: If the same collection is in several paths, the first path in collections_path wins.

ansible-galaxy role list beginner List installed roles and where they are.

Example

bash
ansible-galaxy role list
# /home/jeff/.ansible/roles
- geerlingguy.docker, 7.4.1
ansible-galaxy role install <src> intermediate Install a role from Galaxy, a Git URL or a tarball.

Example

bash
ansible-galaxy role install geerlingguy.docker
ansible-galaxy role install git+https://github.com/orbit/ansible-role-nginx.git,v1.2.0 -p roles/

Tip: Roles have no version ranges; pin an exact tag so a release does not change underneath you.

ansible-galaxy collection init <namespace.name> intermediate Create a collection skeleton (plugins, roles, docs, galaxy.yml) for code you want to share and version.

Example

bash
ansible-galaxy collection init orbit.platform --init-path ./ansible_collections
- Collection orbit.platform was created successfully

Tip: Set namespace, name, version and dependencies in galaxy.yml; the build step reads them from there.

ansible-galaxy collection build intermediate Package a collection directory into a versioned tarball, using the version in galaxy.yml.

Example

bash
cd ansible_collections/orbit/platform
ansible-galaxy collection build --output-path /tmp/dist
Created collection for orbit.platform at /tmp/dist/orbit-platform-1.0.0.tar.gz
ansible-galaxy collection publish <tarball> advanced Upload a built collection to Galaxy or to a private Automation Hub / Galaxy NG server.

Example

bash
ansible-galaxy collection publish /tmp/dist/orbit-platform-1.0.0.tar.gz --api-key "$GALAXY_TOKEN"
ansible-galaxy collection publish /tmp/dist/orbit-platform-1.0.0.tar.gz -s https://hub.orbit.internal/api/galaxy/

Tip: Keep the token in a CI secret; never commit it to ansible.cfg.

ansible-galaxy collection download -r requirements.yml advanced Download collections and their dependencies as tarballs, to install later on a machine without internet access.

Example

bash
ansible-galaxy collection download -r requirements.yml -p ./offline
# On the air-gapped host
cd offline && ansible-galaxy collection install -r requirements.yml

Tip: The download directory gets its own requirements.yml that points at the local tarballs.

ansible-galaxy collection verify <namespace.name> advanced Compare an installed collection against the server copy to detect local modifications.

Example

bash
ansible-galaxy collection verify community.general

Tip: Useful in audits: it shows whether someone edited files inside an installed collection.

Ansible Vault

9 commands

Encrypt passwords, keys and whole variable files so they can live in Git next to the playbooks.

ansible-vault create <file> beginner Create a new encrypted file and open it in $EDITOR.

Example

bash
EDITOR=vim ansible-vault create inventory/group_vars/prod/vault.yml
New Vault password:
Confirm New Vault password:

Tip: Convention: put secrets in vault.yml as vault_db_password and reference them from a plain vars.yml (db_password: "{{ vault_db_password }}") so grep still finds names.

ansible-vault edit <file> beginner Decrypt a vault file into a temporary file, open your editor, and re-encrypt on save.

Example

bash
ansible-vault edit inventory/group_vars/prod/vault.yml
ansible-vault view <file> beginner Print the decrypted content without writing it to disk.

Example

bash
ansible-vault view inventory/group_vars/prod/vault.yml
Vault password:
vault_db_password: s3cr3t-Example
vault_api_token: tok_example_123
ansible-vault encrypt / decrypt <file> beginner Encrypt an existing plain file in place, or turn an encrypted file back into plain text.

Example

bash
ansible-vault encrypt files/orbit-tls.key
head -1 files/orbit-tls.key
ansible-vault decrypt files/orbit-tls.key --output /tmp/orbit-tls.key
Encryption successful
$ANSIBLE_VAULT;1.1;AES256

Tip: ansible.builtin.copy decrypts a vaulted src file automatically (decrypt: true is the default), so encrypted keys and certificates can be deployed as is.

ansible-vault encrypt_string intermediate Encrypt a single value and paste it into an otherwise plain YAML file.

Example

bash
ansible-vault encrypt_string 's3cr3t-Example' --name 'db_password'
# Read the value from stdin so it does not land in shell history
ansible-vault encrypt_string --stdin-name 'api_token'
db_password: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          62313365396662343061393464336163383764373764613633653634306231386433626436623361
          6134333665353966363534333632666535333761666131620a663537646436643839616165643461
Encryption successful
ansible-vault rekey <file> intermediate Change the password of one or more vault files.

Example

bash
ansible-vault rekey inventory/group_vars/*/vault.yml
ansible-vault rekey --new-vault-password-file ~/.vault_pass_new inventory/group_vars/prod/vault.yml
Vault password:
New Vault password:
Confirm New Vault password:
Rekey successful
--ask-vault-pass / -J beginner Prompt for the vault password when running a playbook that uses encrypted data.

Example

bash
ansible-playbook site.yml --ask-vault-pass
ansible-playbook site.yml -J -l prod
--vault-password-file <file> intermediate Read the vault password from a file (or from an executable script that prints it), for CI and automation.

Example

bash
printf '%s\n' "$VAULT_PASSWORD" > ~/.vault_pass && chmod 600 ~/.vault_pass
ansible-playbook site.yml --vault-password-file ~/.vault_pass
# Or set it once
export ANSIBLE_VAULT_PASSWORD_FILE=~/.vault_pass

Tip: If the file is executable Ansible runs it and uses its output, which is how you plug in a password manager or cloud secret store.

--vault-id <label>@<source> advanced Use several vault passwords in one run, each with a label, for example one per environment.

Example

bash
ansible-vault encrypt_string --vault-id prod@prompt 'prod-secret' --name db_password
ansible-playbook site.yml --vault-id dev@~/.vault_dev --vault-id prod@prompt
db_password: !vault |
          $ANSIBLE_VAULT;1.2;AES256;prod
          3831636531376662326435656430313632343739373836633837633234363430616263343433

Tip: The label is stored in the header (format 1.2) as a hint; Ansible still tries the other passwords if the labelled one fails.

Docs & discovery (ansible-doc)

7 commands

Offline documentation for every module and plugin installed on your machine, matching the exact versions you run.

ansible-doc <module> beginner Show the full documentation of a module: options, defaults, return values and examples.

Example

bash
ansible-doc ansible.builtin.copy
# Jump to the examples
ansible-doc ansible.builtin.copy | sed -n '/^EXAMPLES/,$p' | head -20
ansible-doc -s <module> beginner Print a ready-to-paste task snippet with every option and a short comment for each.

Example

bash
ansible-doc -s ansible.builtin.lineinfile | head -12

Tip: Paste the snippet into a task and delete the options you do not need.

ansible-doc -l beginner List every module available, optionally only those of one collection or namespace.

Example

bash
ansible-doc -l | wc -l
ansible-doc -l community.general | grep -i docker
ansible-doc -l ansible.builtin

Tip: Faster than a web search, and it only lists what is actually installed.

ansible-doc -t <type> -l intermediate List or read other plugin types: lookup, filter, test, callback, connection, inventory, become, keyword and more.

Example

bash
ansible-doc -t lookup -l
ansible-doc -t lookup ansible.builtin.file
ansible-doc -t filter ansible.builtin.combine
ansible-doc -t callback -l
ansible.builtin.config        Display the 'resolved' Ansible option values
ansible.builtin.csvfile       read data from a TSV or CSV file
ansible.builtin.dict          returns key/value pair items from dictionaries
ansible.builtin.env           Read the value of environment variables
ansible.builtin.file          read file contents
ansible-doc -t keyword <keyword> intermediate Explain a playbook keyword (serial, become, delegate_to...) and where it can be used.

Example

bash
ansible-doc -t keyword serial
ansible-doc -t keyword -l | head

Tip: Keyword docs say whether a keyword applies to a play, a role, a block or a task.

ansible-doc -F intermediate List modules together with the file each one is loaded from, to find which copy of a collection is used.

Example

bash
ansible-doc -F community.general | grep nmcli
community.general.nmcli      /home/jeff/.ansible/collections/ansible_collections/community/general/plugins/modules/nmcli.py
ansible-doc -j <module> advanced Output the documentation as JSON, for scripts, editors and linters.

Example

bash
ansible-doc -j ansible.builtin.service | python3 -c 'import json,sys; d=json.load(sys.stdin); print(sorted(d["ansible.builtin.service"]["doc"]["options"]))'
['arguments', 'enabled', 'name', 'pattern', 'runlevel', 'sleep', 'state', 'use']

Debugging & output

8 commands

Find out why a task fails: more verbosity, the task debugger, readable output, logs and timing.

ansible.builtin.debug with verbosity beginner Print variables during a run; with verbosity: 1 the message only shows when you pass -v or more.

Example

bash
cat > dbg.yml <<'EOF'
- hosts: web
  tasks:
    - ansible.builtin.command: systemctl is-active orbit-api
      register: api
      changed_when: false
      failed_when: false
    - ansible.builtin.debug:
        var: api
        verbosity: 1
EOF
ansible-playbook dbg.yml -v
ANSIBLE_CALLBACK_RESULT_FORMAT=yaml beginner Print task results as YAML instead of JSON, which makes multi-line stdout and stderr readable.

Example

bash
ANSIBLE_CALLBACK_RESULT_FORMAT=yaml ansible-playbook dbg.yml -v
# Or permanently, in ansible.cfg [defaults]: callback_result_format = yaml
ok: [web01.orbit.internal] =>
    api:
        changed: false
        cmd:
        - systemctl
        - is-active
        - orbit-api
        rc: 0
        stdout: active

Tip: This option of the default callback replaces the old community.general.yaml callback.

debugger: on_failed intermediate Open an interactive debugger when a task fails: inspect variables, change task arguments, and retry.

Example

bash
ANSIBLE_ENABLE_TASK_DEBUGGER=True ansible-playbook site.yml -l web01.orbit.internal
[web01.orbit.internal] TASK: Install nginx (debug)> p task.args
{'name': 'ngnix', 'state': 'present'}
[web01.orbit.internal] TASK: Install nginx (debug)> task.args['name'] = 'nginx'
[web01.orbit.internal] TASK: Install nginx (debug)> redo
changed: [web01.orbit.internal]

Tip: Commands: p (print), redo (r), continue (c), quit (q). Set debugger: on_failed on a play or task to enable it only there.

ANSIBLE_KEEP_REMOTE_FILES=1 advanced Keep the module files Ansible copies to the host so you can inspect or re-run them by hand.

Example

bash
ANSIBLE_KEEP_REMOTE_FILES=1 ansible web01.orbit.internal -m ansible.builtin.ping -vvv 2>&1 | grep -o "/home/deploy/.ansible/tmp/[^ ']*" | head -1
/home/deploy/.ansible/tmp/ansible-tmp-1762430000.12-4242-1234567890

Tip: Delete the directory afterwards; module files can contain arguments, including secrets.

ANSIBLE_LOG_PATH=<file> intermediate Write the run output, with timestamps, to a log file as well as the screen.

Example

bash
ANSIBLE_LOG_PATH=./ansible.log ansible-playbook site.yml
tail -3 ansible.log

Tip: Set log_path in ansible.cfg to keep a history of every run on a shared control node.

callbacks_enabled = ansible.posix.profile_tasks intermediate Show how long each task took and the slowest tasks at the end of the run.

Example

bash
ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks,ansible.posix.timer ansible-playbook site.yml
Friday 06 November 2026  10:15:02 -0300 (0:00:01.214)       0:00:48.511 *****
===============================================================================
nginx : Install nginx ------------------------------------------------------ 21.43s
Gathering Facts ------------------------------------------------------------- 9.87s
orbit : Deploy release ------------------------------------------------------ 6.02s
Playbook run took 0 days, 0 hours, 0 minutes, 48 seconds

Tip: Needs the ansible.posix collection (included in the full ansible package).

ansible.builtin.assert intermediate Fail early with a clear message when an input or a host is not what the playbook expects.

Example

bash
cat > preflight.yml <<'EOF'
- hosts: web
  gather_facts: true
  tasks:
    - ansible.builtin.assert:
        that:
          - release is defined
          - release is match('^[0-9]+$')
          - ansible_facts['mounts'] | selectattr('mount', 'equalto', '/') | map(attribute='size_available') | first > 2000000000
        fail_msg: "release must be a number and / needs 2 GB free"
EOF
ansible-playbook preflight.yml -e release=43
ANSIBLE_DISPLAY_SKIPPED_HOSTS=false beginner Hide skipped tasks from the output so long runs show only what happened.

Example

bash
ANSIBLE_DISPLAY_SKIPPED_HOSTS=false ansible-playbook site.yml
# Even quieter: also hide ok results
ANSIBLE_DISPLAY_OK_HOSTS=false ansible-playbook site.yml

Tip: Both are options of the default callback and can be set in ansible.cfg as display_skipped_hosts and display_ok_hosts.

Connections & performance

10 commands

How Ansible reaches hosts (SSH, local, WinRM, network devices) and the settings that make big runs fast.

ansible_host / ansible_user / ansible_port beginner Connection variables per host or group: the real address, the login user, the port and the key to use.

Example

bash
cat > inventory/host_vars/db01.orbit.internal.yml <<'EOF'
ansible_host: 10.0.2.15
ansible_user: deploy
ansible_port: 22
ansible_ssh_private_key_file: ~/.ssh/orbit_ed25519
EOF
ansible db01.orbit.internal -m ansible.builtin.ping
-c local / ansible_connection=local beginner Run tasks on the control node itself without SSH.

Example

bash
ansible-playbook -i localhost, -c local workstation.yml
ansible localhost -m ansible.builtin.setup -a "filter=ansible_os_family"

Tip: localhost is implicit: you can target it without listing it in the inventory.

ansible_python_interpreter intermediate Choose the Python used on a managed node; the default interpreter discovery picks one and warns unless told to be silent.

Example

bash
ansible legacy01 -m ansible.builtin.ping -e ansible_python_interpreter=/usr/bin/python3.9
# ansible.cfg [defaults]: interpreter_python = auto_silent

Tip: Hosts without Python can be bootstrapped with the raw module: ansible new01 -b -m ansible.builtin.raw -a "dnf install -y python3".

ansible.builtin.raw intermediate Send a plain command over SSH with no Python on the target, for bootstrapping and appliances.

Example

bash
ansible new01.orbit.internal -u root -k -m ansible.builtin.raw -a "dnf install -y python3"
new01.orbit.internal | CHANGED | rc=0 >>
Complete!
Shared connection to 10.0.1.50 closed.
ansible_connection=winrm / ssh (Windows) advanced Manage Windows hosts over WinRM or OpenSSH with the ansible.windows collection.

Example

bash
cat > inventory/windows.yml <<'EOF'
windows:
  hosts:
    win01.orbit.internal:
  vars:
    ansible_connection: winrm
    ansible_winrm_transport: ntlm
    ansible_user: Administrator
EOF
ansible windows -i inventory/windows.yml -m ansible.windows.win_ping -k

Tip: Windows modules are separate (win_copy, win_service, win_package...); Linux modules like ansible.builtin.copy do not run there.

ansible_connection=ansible.netcommon.network_cli advanced Manage switches and routers over their CLI; the network_os variable selects the platform plugin.

Example

bash
cat > inventory/network.yml <<'EOF'
switches:
  hosts:
    sw01.orbit.internal:
  vars:
    ansible_connection: ansible.netcommon.network_cli
    ansible_network_os: cisco.ios.ios
    ansible_user: netops
EOF
ansible switches -i inventory/network.yml -m cisco.ios.ios_command -a "commands='show version'" -k

Tip: Network modules run on the control node and talk to the device, so the device needs no Python.

pipelining = true intermediate Send modules over the open SSH session instead of copying a file first: fewer round trips, noticeably faster runs.

Example

bash
ANSIBLE_PIPELINING=True ansible-playbook site.yml
# ansible.cfg
# [ssh_connection]
# pipelining = true

Tip: With become, sudo on the hosts must not require a TTY (no Defaults requiretty in sudoers).

ssh_args ControlPersist intermediate Reuse SSH connections between tasks; Ansible's default already enables ControlMaster with a 60s ControlPersist.

Example

bash
ANSIBLE_SSH_ARGS='-C -o ControlMaster=auto -o ControlPersist=300s' ansible-playbook site.yml
# ansible.cfg
# [ssh_connection]
# ssh_args = -C -o ControlMaster=auto -o ControlPersist=300s

Tip: Setting ssh_args replaces the default value, so keep ControlMaster and ControlPersist in your own line.

strategy: free advanced Let each host run through the tasks as fast as it can instead of waiting for all hosts at every task (the linear default).

Example

bash
cat > patch.yml <<'EOF'
- hosts: all
  strategy: free
  become: true
  tasks:
    - ansible.builtin.dnf:
        name: "*"
        state: latest
EOF
ansible-playbook patch.yml -f 30

Tip: Output becomes interleaved between hosts; use it for independent hosts, not for ordered rollouts.

fact caching (jsonfile, redis) advanced Store gathered facts between runs so later playbooks can skip gathering or read facts of hosts they did not contact.

Example

bash
export ANSIBLE_GATHERING=smart
export ANSIBLE_CACHE_PLUGIN=ansible.builtin.jsonfile
export ANSIBLE_CACHE_PLUGIN_CONNECTION=~/.cache/ansible/facts
export ANSIBLE_CACHE_PLUGIN_TIMEOUT=86400
ansible-playbook site.yml && ls ~/.cache/ansible/facts
# ansible.cfg [defaults]: gathering, fact_caching, fact_caching_connection, fact_caching_timeout
db01.orbit.internal  web01.orbit.internal  web02.orbit.internal

Tip: gathering = smart only gathers when the cache has no facts for a host. Use --flush-cache to refresh.

Linting & testing

8 commands

Catch mistakes before they reach servers: ansible-lint for style and bugs, Molecule for role tests, ansible-test for collections.

ansible-lint beginner Check playbooks, roles and collections for bugs, deprecated syntax and style problems.

Example

bash
pipx install ansible-lint
ansible-lint
ansible-lint site.yml roles/nginx
name[missing]: All tasks should be named.
roles/nginx/tasks/main.yml:12 Task/Handler: ansible.builtin.service name=nginx state=started

fqcn[action-core]: Use FQCN for builtin module actions (service).
roles/nginx/tasks/main.yml:12 Use `ansible.builtin.service` or `ansible.legacy.service` instead.

Failed: 2 failure(s), 0 warning(s) in 9 files processed of 9 encountered. Last profile that met the validation criteria was 'min'.
ansible-lint --fix intermediate Let ansible-lint rewrite the files it knows how to fix (FQCN, YAML formatting, truthy values...).

Example

bash
ansible-lint --fix
git diff --stat

Tip: Run it on a clean Git tree and review the diff; the rewrite also reformats YAML.

ansible-lint --profile <name> intermediate Apply a predefined rule set: min, basic, moderate, safety, shared, production.

Example

bash
ansible-lint --profile production
cat > .ansible-lint <<'EOF'
profile: moderate
exclude_paths:
  - .cache/
  - collections/
skip_list:
  - yaml[line-length]
EOF
ansible-lint

Tip: Raise the profile step by step on old repositories instead of fixing hundreds of findings at once.

ansible-lint -L / -T intermediate List all rules (-L) or all tags (-T) to decide what to skip or enforce.

Example

bash
ansible-lint -L | head
ansible-lint -T
molecule init scenario advanced Add a Molecule test scenario to a role or collection: create test instances, converge, verify, destroy.

Example

bash
pipx install molecule
pipx inject molecule 'molecule-plugins[docker]'
cd roles/nginx && molecule init scenario default

Tip: The scenario lives in molecule/default/ with molecule.yml (platforms, driver), converge.yml and verify.yml.

molecule test advanced Run the full scenario: lint, create, converge, idempotence check, verify and destroy.

Example

bash
molecule test
# Keep the instance to debug a failure
molecule test --destroy=never

Tip: The idempotence step re-runs the role and fails if anything reports changed on the second run.

molecule converge / verify / login / destroy advanced The development loop: apply the role, run the checks, open a shell in the instance, clean up.

Example

bash
molecule converge
molecule verify
molecule login -h instance
molecule destroy
ansible-test sanity / units / integration advanced The test runner for collections: sanity checks (docs, imports, PEP 8...), Python unit tests and integration targets.

Example

bash
cd ansible_collections/orbit/platform
ansible-test sanity --docker default -v
ansible-test units --docker default
ansible-test integration --docker default nginx_site

Tip: It must run from inside an ansible_collections/<namespace>/<name> directory; --docker runs everything in a known-good container.

Execution environments & other CLIs

6 commands

ansible-navigator and ansible-builder for container-based execution environments, plus ansible-pull and ansible-console.

ansible-navigator run <playbook> intermediate Run a playbook inside an execution environment (a container with ansible-core, collections and Python deps).

Example

bash
pipx install ansible-navigator
ansible-navigator run site.yml -i inventory/ -m stdout
# Interactive text UI: drill into plays, tasks and results
ansible-navigator run site.yml -i inventory/

Tip: Each run saves an artifact JSON; ansible-navigator replay <file> reopens it later, handy for reviewing CI runs.

ansible-navigator run --ee false intermediate Use ansible-navigator with the Ansible installed on the host instead of a container.

Example

bash
ansible-navigator run site.yml -i inventory/ -m stdout --ee false
# A specific image
ansible-navigator run site.yml -m stdout --eei registry.orbit.internal/orbit-ee:1.0
ansible-navigator collections / doc / inventory intermediate Browse collections, docs and the inventory as seen from inside the execution environment.

Example

bash
ansible-navigator collections
ansible-navigator doc ansible.builtin.copy -m stdout
ansible-navigator inventory -i inventory/

Tip: Settings can live in ansible-navigator.yml at the project root, so the whole team uses the same image and mode.

ansible-builder build advanced Build an execution environment image from execution-environment.yml (base image, collections, Python and system packages).

Example

bash
pipx install ansible-builder
cat > execution-environment.yml <<'EOF'
version: 3
images:
  base_image:
    name: quay.io/fedora/fedora:latest
dependencies:
  ansible_core:
    package_pip: ansible-core
  ansible_runner:
    package_pip: ansible-runner
  galaxy: requirements.yml
  python: requirements.txt
  system: bindep.txt
EOF
ansible-builder build -t registry.orbit.internal/orbit-ee:1.0 -v 3

Tip: ansible-builder create only writes the build context (Containerfile and files) without building, useful for custom pipelines.

ansible-pull advanced Invert the model: each host clones a Git repository and runs a playbook against itself, for example from cron.

Example

bash
ansible-pull -U https://github.com/orbit/ansible-config.git -C main -d /var/lib/ansible/local -i localhost, local.yml
# Only run when the repository changed
ansible-pull -U https://github.com/orbit/ansible-config.git -o local.yml

Tip: Good for large fleets or hosts behind NAT that the control node cannot reach.

ansible-console intermediate An interactive shell for ad-hoc work: pick hosts once, then type module names and arguments.

Example

bash
ansible-console -i inventory/ web -b
Welcome to the ansible console. Type help or ? to list commands.

jeff@web (2)[f:5]# shell systemctl is-active nginx
web01.orbit.internal | CHANGED | rc=0 >>
active
web02.orbit.internal | CHANGED | rc=0 >>
active
jeff@web (2)[f:5]# cd db
jeff@db (1)[f:5]# ping

Tip: cd <pattern> changes the target hosts, forks <n> changes parallelism, exit leaves.

↑ ↓ navigate Enter open Esc close