← All cheatsheets

IaC

Ansible — inventory, playbooks, and idempotent runs

Agentless config management with Ansible: define hosts in inventory, run ad-hoc modules or playbooks over SSH, and converge to desired state idempotently — always dry-run with --check --diff before applying.

Docs-checkedansibleconfig-managementplaybooksidempotencyinventory

Quick reference — reach for these first

pingansible all -i INVENTORY -m pingAd-hoc reachability + Python check on every host
checkansible-playbook SITE.yml -i INVENTORY --check --diffDry run; print what WOULD change, no writes
runansible-playbook SITE.yml -i INVENTORYApply the play; converge hosts to desired state
scopeansible-playbook SITE.yml -i INVENTORY --limit HOST --tags TAGRestrict to some hosts and some tagged tasks
vaultansible-vault encrypt SECRETS.ymlEncrypt a secrets file at rest (edit with ansible-vault edit)

How an Ansible run flows: control node → inventory → managed hosts

Ansible run flow from control node to managed hostsControl node runs ansible-playbook, reads inventory, and over SSH pushes modules that enforce idempotent desired state; check mode previews without writing.Control nodeansible /ansible-playbookno agent on hostsInventorystatic INI/YAMLor dynamic pluginweb1 (group: web)module pushed → run → removedweb2 (group: web)enforce desired statedb1 (group: db)2nd run → changed=0over SSH--check --diff: preview changes, no writes

Text equivalent: A left box labeled Control node runs ansible and ansible-playbook. It reads an Inventory (static INI/YAML or a dynamic plugin) that resolves to groups of managed hosts. Over SSH, Ansible pushes a module to each host, runs it to enforce desired state, and removes it. A dashed check-mode arrow shows --check/--diff previewing changes without writing. On a second run, modules report changed=0 because the hosts already match desired state (idempotency).

Common tasks

Task · Command · Check / expect

TaskCommandCheck / expect
CONFIRM target context: resolve inventory to the actual host treeansible-inventory -i INVENTORY --graphGroups and host names match the environment you intend (not prod by accident)
Preview which hosts a pattern will touch (no changes)ansible WEBSERVERS -i INVENTORY --list-hostsOnly the hosts you expect are listed
Test connectivity and remote Pythonansible all -i INVENTORY -m pingEach host returns "ping": "pong" with SUCCESS
Run a safe ad-hoc command (read-only module)ansible all -i INVENTORY -m command -a 'uptime'rc=0 and stdout per host; command module is not idempotent, keep it read-only
Gather and inspect facts for one hostansible HOST -i INVENTORY -m setup -a 'filter=ansible_distribution*'OS/distribution facts return; use these in when: conditions
Validate playbook syntax before any runansible-playbook SITE.yml --syntax-checkPrints the playbook path with no YAML/parse errors
Dry run and show the diff (PREVIEW, no changes)ansible-playbook SITE.yml -i INVENTORY --check --diffPLAY RECAP shows would-be changed=N; nothing is actually modified
List the tasks/tags a play containsansible-playbook SITE.yml --list-tasks --list-tagsConfirms task names and tag names before using --tags
Apply to a single host first (blast-radius control)ansible-playbook SITE.yml -i INVENTORY --limit HOSTchanged>0 on first apply; failed=0 in PLAY RECAP
CHANGES PRODUCTION: run a tagged subset across a groupansible-playbook SITE.yml -i INVENTORY --limit WEBSERVERS --tags deployOnly deploy-tagged tasks run; handlers flush at play end
Escalate privileges when a task needs rootansible-playbook SITE.yml -i INVENTORY --become --ask-become-passPrivileged tasks succeed; prefer become: true in the play over CLI flags
Encrypt secrets and run with the vault passwordansible-playbook SITE.yml -i INVENTORY -e @SECRETS.yml --ask-vault-passPlay runs; vaulted values never printed in output
Prove idempotency: run the SAME play a second timeansible-playbook SITE.yml -i INVENTORYPLAY RECAP shows changed=0 — converged, nothing to do

Write a small play, dry-run it, apply it, then prove idempotency

check-then-apply

1
Define an inventory with one web host group
printf '[web]\nweb1 ansible_host=203.0.113.10 ansible_user=deploy\n' > inventory.ini
2
Confirm the target context before touching anything
ansible-inventory -i inventory.ini --graph
# @all:
#   |--@web:
#   |  |--web1
3
Write a minimal, idempotent playbook (package + templated file)
cat > site.yml <<'YAML'
- name: Web baseline
  hosts: web
  become: true
  tasks:
    - name: Ensure nginx present
      ansible.builtin.package: { name: nginx, state: present }
    - name: Deploy index page
      ansible.builtin.copy:
        content: "hello from {{ inventory_hostname }}\n"
        dest: /var/www/html/index.html
YAML
4
Syntax-check, then DRY RUN with diff — no changes are written
ansible-playbook site.yml -i inventory.ini --syntax-check && ansible-playbook site.yml -i inventory.ini --check --diff
# PLAY RECAP
# web1 : ok=3 changed=2 unreachable=0 failed=0  (check mode)
5
Apply for real (first convergence)
ansible-playbook site.yml -i inventory.ini
# web1 : ok=3 changed=2 unreachable=0 failed=0
6
VERIFY idempotency: run the identical play again
ansible-playbook site.yml -i inventory.ini
# web1 : ok=3 changed=0 unreachable=0 failed=0  <- changed=0 == converged

Troubleshooting — symptom → first check → next check

SymptomFirst checkEstablishesNext check
Permission denied (publickey) / auth fails on connectssh -o BatchMode=yes USER@HOST true, then re-run with ansible ... -vvvWhether it is an SSH key/user problem (outside Ansible) vs. an Ansible config issueSet ansible_user / ansible_ssh_private_key_file in inventory or use --private-key; load the key into ssh-agent
Host flagged UNREACHABLE in the recapansible HOST -i INVENTORY -m ping -vvvIf the transport (DNS, port 22, firewall, host key) is the failure, not a taskFix name resolution / network, or set ansible_host and ansible_port; accept the host key or set host_key_checking appropriately
A task reports changed=yes on every run (not idempotent)Re-run with --check --diff and read which task reports the changeWhether a command/shell task is standing in for a proper moduleReplace command/shell with a stateful module (copy, template, file, package, service) or add creates=/removes= guards
Task fails with permission denied writing/installing as non-rootInspect the failing task for become; run that play with --become --ask-become-passThat privilege escalation, not the module args, is missingAdd become: true (and become_user if needed) to the play or task; ensure sudo is configured on the host
Playbook aborts at parse time with a YAML/syntax erroransible-playbook SITE.yml --syntax-checkThe error is structural (indentation, mapping) before any host is touchedFix the reported line; validate indentation and quoting, then re-run --syntax-check until clean
Runs are very slow across many hostsTime a run and check forks: ansible-config dump | grep -i forksWhether low parallelism or repeated fact gathering is the costRaise forks (-f 20 or in ansible.cfg), set gather_facts: false where unneeded, and enable fact caching / SSH pipelining

References

ansible-core 2.16+ on a Linux/macOS control node; managed hosts reachable over SSH with Python 3 present.

Related sheets