91.5 Idempotence and reading ok, changed and PLAY RECAP
Story (fictional teaching scenario). At a fictional bank IT team in Pune, Olga from Kyiv was scared to run a playbook twice. "Will it install everything again?" Arvind showed her two runs. The first said changed. The second said ok everywhere and changed nothing. That is idempotence: you describe the end state, and Ansible only acts when the server is different from it.
Why
If running twice is safe, you can run often, fix drift and recover after a half-failed run without fear.
What
- Idempotent — Running the same task many times gives the same end result and changes nothing after the first time.
- ok — The task ran and the server was already correct.
- changed — The task had to change something.
- failed / unreachable / skipped — Task error, could not connect, or a condition said "not here".
- PLAY RECAP — The summary table at the end, one line per host.
- changed_when — Lets you tell Ansible when a command really changes something.
How
- Prefer state-based modules (
file,copy,template,package) overcommandorshell. - Run the playbook twice. The second run should show
changed=0. - For
commandtasks that only read, addchanged_when: false.
Example 1: First run
ansible-playbook site.yml
Output (tested on ansible-core 2.22.0, local practice lab)
TASK [Make app folder]
changed: [web2]
changed: [web1]
TASK [Write config from template]
changed: [web2]
changed: [web1]
PLAY RECAP
web1 : ok=3 changed=2 unreachable=0 failed=0 skipped=0
web2 : ok=3 changed=2 unreachable=0 failed=0 skipped=0
What it means: Two tasks changed something on each host. ok=3 counts every task that finished well, including the changed ones and one handler (lesson 8).
Example 2: Same command again
Output (tested on ansible-core 2.22.0, local practice lab)
TASK [Make app folder]
ok: [web2]
ok: [web1]
TASK [Write config from template]
ok: [web2]
ok: [web1]
PLAY RECAP
web1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0
web2 : ok=2 changed=0 unreachable=0 failed=0 skipped=0
What it means: Nothing was different, so nothing changed and the handler did not run. This is idempotence you can see.
Ravindra Bagale's Tip
Your test for a good playbook: run it twice. If the second run shows changed above 0, find out why.
चांगल्या playbook ची test: दोनदा चालवा. दुसऱ्या run मध्ये changed 0 पेक्षा जास्त आलं तर कारण शोधा.
अच्छे playbook की test: दो बार चलाओ. दूसरे run में changed 0 से ज़्यादा आए तो वजह ढूँढो.
Did you understand? Let us try it once more.