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 == 200The 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 changedwhen: 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-eis truthy.-e "enable_flag=false"passes a string, and a non-empty string tests true.when: enable_flag | boolfixes it. - Use the tests, not
.changed.result is changed,result is failed,result is succeededread the registered result's semantics;result.changed == trueworks but is the brittle spelling. whendoesn't seerescuestate. Ablock/rescuesection's failure facts live inansible_failed_task/ansible_failed_result, not in yourwhen.
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 changedlisten: 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
changedoncommand/shellis a lie unless you setchanged_when— and handler notifications depend on it being true.import_tasksis resolved at parse time and can't be looped;include_tasksis dynamic — it can takeloop, 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 aserial: 30%play runs at the end of each 30% slice, which is exactly what a rolling restart wants.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Self-Hosting Prometheus and Grafana: Infrastructure Monitoring That Actually Works
Build a production-grade monitoring stack with Prometheus and Grafana from scratch. Covers architecture, Docker Compose deployment, Node Exporter, alerting with Alertmanager, PromQL from basics to advanced, pre-built dashboards, and everything SudoSecurity uses to monitor its own infrastructure.
Zero Trust Everything: The Complete Guide to Self-Hosting Teleport for Secure Infrastructure Access
SudoSecurity runs Teleport internally for everything — admin panel access, secure database connections, Kubernetes, and zero-trust philosophy across our entire team. This is the complete technical guide to installing, configuring, and running your own self-hosted Teleport cluster from scratch.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
AWS Emulator Puts AWS on Your Laptop. Keep Your IAM Tests Off It.
AWS released AWS Emulator on November 11, a free local server that answers AWS API calls on 127.0.0.1 with per-run keys and fresh certificates.