Skip to content

Lesson 6 of 13 · 22m

Loops, Handlers, and Conditionals Without the Traps

loop, until/retries, Jinja-truthy when clauses, and the handler lifecycle that decides whether your reload ever fires.

Two questions expose Ansible experience faster than any certification: "why didn't your handler run?" and "why is your when never true?" Neither is a syntax error. Both are lifecycle misunderstandings — the YAML parses, the playbook runs, it just doesn't mean what you wrote.

loop: the one iteration syntax that matters

- name: Create service accounts
  ansible.builtin.user:
    name: "{{ item.name }}"
    groups: "{{ item.groups }}"
    state: present
  loop:
    - { name: deploy, groups: "docker,sudo" }
    - { name: backup, groups: "backup" }

loop replaced the with_items/with_dict/with_fileglob zoo — those still work because they're lookup-plugin calls wearing a with_ costume, but new code uses loop, and with_* on modern ansible-lint gets flagged on sight. When item is a fat dict, the log line becomes unreadable; loop_control: label: "{{ item.name }}" keeps it human:

  loop: "{{ app_instances }}"
  loop_control:
    label: "{{ item.name }} ({{ item.region }})"

loop_control also carries pause: (seconds between iterations — how you keep a rate-limited API happy) and index_var/loop_var for nested loops that would otherwise collide on item.

Retry loops: until/retries/delay

- name: Wait for the health endpoint
  ansible.builtin.uri:
    url: "http://{{ inventory_hostname }}:8080/healthz"
    status_code: 200
  register: health
  retries: 12
  delay: 10
  until: health.status == 200

The task re-runs until until is true or retries exhaust — 12 retries at 10s gives a cold-starting JVM about two minutes of runway. The pattern pairs with register because until needs something to inspect. Without it, "deploy then immediately curl" is a coin flip against startup time.

when: Jinja truthiness, not Python

- name: Debian-only package
  ansible.builtin.apt: { name: htop, state: present }
  when: ansible_facts['os_family'] == 'Debian'

- name: Restart if the config actually drifted
  ansible.builtin.service: { name: app, state: restarted }
  when: config_result is changed

when: evaluates a Jinja2 expression per task, per host — one host's os_family says RedHat and the task skips that host while the Debian boxes proceed. That's the mechanism behind "reboot only the nodes that need it" in a single task.

The traps, in order of how often they produce a bug ticket:

  • Never wrap when: in {{ }}. It's already a Jinja context. when: "{{ x }} == 'y'" stringifies the whole expression and evaluates a non-empty string — which is truthy — so the task always runs. This is the most common Ansible bug in existence.
  • A string "false" from -e is truthy. -e "enable_flag=false" passes a string, and a non-empty string tests true. when: enable_flag | bool fixes it.
  • Use the tests, not .changed. result is changed, result is failed, result is succeeded read the registered result's semantics; result.changed == true works but is the brittle spelling.
  • when doesn't see rescue state. A block/rescue section's failure facts live in ansible_failed_task/ansible_failed_result, not in your when.

Handlers: the notify lifecycle, stated precisely

Handlers run once, at the end of the play, only if a task that reported changed notified them. Notify five times, run once. Order is definition order in handlers:, not notification order — notify B then A, A still runs first if it's defined first.

handlers:
  - name: Reload nginx
    ansible.builtin.service: { name: nginx, state: reloaded }
    listen: web config changed

  - name: Purge CDN cache
    ansible.builtin.uri: { url: "https://cdn.acme.corp/purge", method: POST }
    listen: web config changed

listen: topics let one notification fan out to several handlers — "web config changed" reloads nginx and purges the edge.

The failure mode that gets everyone once: a task fails on a host after your config task notified, and the pending handler never fires. The host keeps running the old config. The next playbook run sees the config already in place, reports ok, notifies nothing — the reload is permanently orphaned. Two fixes: meta: flush_handlers as a task where you need the reload mid-play, or force_handlers: true on the play (--force-handlers on the CLI) so notified handlers run despite the failure.

Field notes

  • changed on command/shell is a lie unless you set changed_when — and handler notifications depend on it being true.
  • import_tasks is resolved at parse time and can't be looped; include_tasks is dynamic — it can take loop, and it's the only way to make a whole task file conditional per iteration.
  • serial-batched plays re-fire handlers per batch — a reload notification inside a serial: 30% play runs at the end of each 30% slice, which is exactly what a rolling restart wants.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.