Ravindra BagaleCourses & study guides मराठी

Chapter 91: Ansible Deep Dive

DevOps

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.

First run changes what is missing. Second run finds nothing to do and reports ok, changed=0.
First run changes what is missing. Second run finds nothing to do and reports ok, changed=0.

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

  1. Prefer state-based modules (file, copy, template, package) over command or shell.
  2. Run the playbook twice. The second run should show changed=0.
  3. For command tasks that only read, add changed_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.

Did you understand? Let us try it once more.