Skip to content

Lesson 4 of 13 · 24m

Playbooks and the Idempotency Contract

Plays, tasks, and the changed/ok/failed contract — why modules beat shell, and how check+diff makes a run reviewable.

Run the playbook twice. The second run should be a wall of green — ok, nothing changed. That's the senior-engineer smell test, and it's how you find out whether your automation is honest before production does. A task that reports changed on an already-converged system is telling a lie, and the lie always compounds: it's "we restarted nginx 400 times across the rolling deploy" or "the same cron line got appended 40 times because nobody noticed."

What a play actually is

# playbooks/web.yml
- name: Configure web tier
  hosts: webservers
  become: true

  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true

    - name: Ship site config
      ansible.builtin.template:
        src: nginx-site.conf.j2
        dest: /etc/nginx/sites-available/acme.conf
        mode: "0644"
      notify: Reload nginx

  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded

A play binds a host pattern (hosts:) to an ordered list of tasks:. A playbook is a list of plays — this one could be followed by Configure db tier in the same file, each play mapping its own hosts to its own work. notify: is the handshake: a task that reports changed flags the named handler, which runs once at the end of the play. Change nothing, notify nothing — the handler's run count is downstream of honesty, not syntax.

Modules inspect, commands execute

command and shell run a string. They cannot know what changed, so they report changed every time — which burns the one signal Ansible actually sells you. Modules do the opposite: they query current state, compare to declared state, act only on the delta, and report truthfully.

# dishonest — appends a duplicate line every single run, always reports changed
- name: Add repo
  ansible.builtin.shell: echo "deb ..." >> /etc/apt/sources.list.d/pgdg.list

# honest — checks whether the repo stanza exists, writes only if not
- name: Add repo
  ansible.builtin.deb822_repository:
    name: pgdg
    types: [deb]
    uris: "https://apt.postgresql.org/pub/repos/apt"
    suites: "{{ ansible_facts['distribution_release'] }}-pgdg"
    components: [main]
    state: present

(apt_key is gone — deb822_repository writes the modern .sources format.) Sometimes a command is genuinely the right tool. Then you restore honesty by hand: creates:/removes: skip the task when an artifact exists, or run it, register the result, and set changed_when:/failed_when: to teach Ansible what the output means:

- name: Rebuild the index
  ansible.builtin.command: /opt/app/bin/reindex --all
  register: reindex
  changed_when: "'reindexed 0 documents' not in reindex.stdout"

A task that reports ok when it did nothing is a promise kept. A task that reports changed when it did nothing is a debt collector — it will notify handlers, page people, and corrupt your --check diffs.

Idempotency is per-attribute, not per-resource

state: present on apt means "installed", not "this version" — it will happily leave nginx 1.18 while 1.24 exists. state: latest is a different promise with different blast radius (a surprise apt upgrade inside a config run). Choose per attribute: present for "must exist", latest only where you actually want drift chased, pinned version: for the things that must not move.

The same distinction applies to lineinfile (which edits a line — run it twice with different regexp misses and you own two lines) versus template (which owns the file — the strongest idempotency guarantee of all, because the whole file is the declared state).

Rehearsing safely

ansible-playbook web.yml --check --diff

--check asks each module "would you change?" without doing it — apt and template answer honestly, command is skipped by default because it can't know. --diff prints the before/after for file mutations. Run check+diff in CI on every pull request and "what does this playbook do?" becomes a code review of a diff, not a reading of YAML.

Two footguns worth the scar tissue: check mode is advisory, so anything gated when: not ansible_check_mode or a command feeding a register will skip — a playbook that only works in check mode is its own genre of surprise. And --syntax-check validates the YAML, nothing else; it tells you the file parses, not that it's true.

Field notes

  • name: on every task. The task name is the log line a tired on-call reads at 3 a.m.; "TASK [apt]" explains nothing.
  • A failed host drops out of that play while the others continue — any_errors_fatal, serial, and max_fail_percentage exist for when that default is wrong.
  • import_tasks resolves at parse time (static, tag-friendly); include_tasks resolves at run time (dynamic, can be looped). Picking wrong is how tags silently cover zero tasks.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.