Skip to content

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 != 0

failed_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 immediately register and 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 current serial batch 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=60s

The payoffs, honestly ranked:

  1. 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 = 50 is the single highest-payoff line in Ansible tuning; beyond ~100 watch control-node CPU and the far side's SSH max-startups.
  2. ControlPersist — multiplexes tasks over one TCP connection per host per 60s window; kills the per-task handshake that dominates small-task plays.
  3. pipelining — pipes module source over stdin instead of sftp+chmod+exec+rm; needs requiretty absent from sudoers (default true on modern distros — check yours).
  4. gathering = smart + a real fact cache — setup per host per play is expensive; a jsonfile or redis cache 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: true or meta: flush_handlers is how the reload still happens.
  • delegate_to: localhost + run_once: true does something once total; without run_once it's once per host, which is how "create one LB pool" becomes "create the pool on all 30 web nodes."
  • async/poll are for tasks outliving the SSH session — covered with the rolling-update choreography; poll: 0 without a later async_status is a rumor, not a result.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.