Lesson 7 / 26

Idempotency

Show that running a playbook twice leaves the system unchanged the second time.

Run it again safely

Idempotency is Ansible's most valuable property: modules check the current state and act only if it differs from what you asked for. That makes playbooks safe to run repeatedly, from CI, on a schedule, or to repair drift when someone changed a server by hand. The command and shell modules are not inherently idempotent; use a purpose-built module when one exists, or add creates:, removes: or changed_when: so Ansible can tell whether anything really changed.

Second run, run for real

I ran the same playbook again. Every task reports ok, the handler does not fire, and the recap shows changed=0 for both hosts.

ansible-playbook -i inventory.ini site.yml

Output:

PLAY RECAP *********************************************************************
web1                       : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web2                       : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Prefer modules over shell

ansible.builtin.apt, file, copy, user, service and many more describe state. shell: apt install nginx would report changed every time.

Quick check: Why is idempotency valuable?

  • Playbooks can be re-run safely and repair drift
  • It makes tasks slower
  • It removes the need for inventory
  • It only works on Windows
Answer

Playbooks can be re-run safely and repair drift — Declared state means repeated runs converge to the same result.