Lesson 10 of 13 · 25m
Failure Handling, Execution Strategies, and Speed
block/rescue/always, failed_when honesty, and the forks/pipelining/fact-cache knobs that turn a 45-minute run into a 6-minute one.
Two production scars carry this lesson's material. One: a deploy playbook that kept going after a database migration failed on the primary — an ignore_errors: true someone left behind, so every replica ran migrations against a half-applied schema. Two: a "why does this take 45 minutes" audit that found forks: 5, no pipelining, no SSH multiplexing, and gather_facts running on plays that never read a fact. Failure semantics and execution speed are the same discipline: controlling when things run and what the run does about it.
block/rescue/always: structured failure, finally
- name: Apply the migration safely
block:
- name: Stop writes
ansible.builtin.service: { name: app, state: stopped }
- name: Run migration
ansible.builtin.command: /opt/app/bin/migrate
rescue:
- name: Roll the schema back
ansible.builtin.command: /opt/app/bin/migrate --rollback
- name: Bring the app back
ansible.builtin.service: { name: app, state: started }
always:
- name: Tell the on-call
ansible.builtin.command: /opt/bin/notify-oncall "migration task finished"rescue: runs when anything in block: fails — with ansible_failed_task and ansible_failed_result populated for the autopsy; always: runs regardless, the finally: clause. This is the replacement for "the playbook died mid-flight and left the app stopped," which is the failure mode that converts a retryable error into an outage.
Teaching Ansible what failure means
- name: Check cert expiry (data, not failure)
ansible.builtin.command: openssl x509 -checkend 604800 -noout -in /etc/ssl/acme.crt
register: cert_check
failed_when: false # non-zero rc is information
changed_when: false
- name: Renew if within a week of expiry
ansible.builtin.command: /usr/bin/certbot renew --cert-name acme
when: cert_check.rc != 0failed_when/changed_when are how you translate a command's semantics into Ansible's. openssl -checkend exits non-zero to say "expires within N seconds" — that's a signal, not a failure, and failed_when: false keeps the run green while a later task acts on the data.
The other two knobs form a spectrum:
ignore_errors: true— "I refuse to know this failed." Legitimate exactly once: when you immediatelyregisterand inspect the result yourself. As a leave-behind, it's the replica-migrations scar above.any_errors_fatal: true— the opposite extreme: one host failing kills the entire run on every host. Correct for a fleet-wide schema migration where partial success is worse than none; wrong for routine config drift where one sick node shouldn't stop ninety-nine healthy ones.max_fail_percentage— the middle: abort the run once more than N% of the currentserialbatch has failed. (Batching itself lives in the delegation lesson — the failure knob lives here.)
Execution strategies: who's allowed to run ahead
strategy: linear (the default) keeps hosts lockstep — every host finishes task N before any starts task N+1. strategy: free lets each host run ahead independently — right for independent config work, wrong for orchestrated sequences, and with a handler caveat: under free, notified handlers can fire at non-batch boundaries, which is rarely what a reload wants.
The speed knobs, in order of payoff
# ansible.cfg
[defaults]
forks = 50 # the default of 5 is why you're slow
gathering = smart # only gather when the fact cache is stale
fact_caching = jsonfile
fact_caching_connection = ~/.ansible/facts
[ssh_connection]
pipelining = True # modules via stdin — no sftp round trip per task
ssh_args = -o ControlMaster=auto -o ControlPersist=60sThe payoffs, honestly ranked:
forks— default 5 means 5 hosts at a time, period. On 500 hosts with 30 tasks each that's the 45-minute run by definition.forks = 50is the single highest-payoff line in Ansible tuning; beyond ~100 watch control-node CPU and the far side's SSH max-startups.ControlPersist— multiplexes tasks over one TCP connection per host per 60s window; kills the per-task handshake that dominates small-task plays.pipelining— pipes module source over stdin instead of sftp+chmod+exec+rm; needsrequirettyabsent from sudoers (default true on modern distros — check yours).gathering = smart+ a real fact cache —setupper host per play is expensive; ajsonfileorrediscache makes facts durable.
Profile before reaching further: callbacks_enabled = profile_tasks (and timer) in ansible.cfg prints per-task timing at the end of every run. When the config knobs stop paying, Mitogen (a strategy plugin that keeps a persistent Python interpreter per host) is the real next step; ansible-pull is the architectural one — nodes pull a git checkout and run locally, which sidesteps control-node scaling entirely.
Field notes
- A host that fails drops out of the play and loses its pending handler notifications —
force_handlers: trueormeta: flush_handlersis how the reload still happens. delegate_to: localhost+run_once: truedoes something once total; withoutrun_onceit's once per host, which is how "create one LB pool" becomes "create the pool on all 30 web nodes."async/pollare for tasks outliving the SSH session — covered with the rolling-update choreography;poll: 0without a laterasync_statusis a rumor, not a result.
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.