Blocks, Rescue, and Always¶
Section status: outline
This page is scoped but not yet written in full prose. The sections below define what it will cover.
Why This Exists¶
A flat task list has no concept of "if any of these three tasks fail, do this instead" — block/rescue/always is Ansible's answer, modeled loosely on try/except/finally from general-purpose languages, but evaluated per host.
What It Will Cover¶
block:to group related tasks (sharedwhen:,become:, tags applied once to the whole group)rescue:— runs only if a task inside theblockfails; the failure is then considered handled unlessrescueitself fails or explicitly re-raisesalways:— runs regardless of whether the block succeeded, failed, or was rescuedansible_failed_task/ansible_failed_resultmagic variables available insiderescue:- A worked example: attempt a deployment in
block, roll back inrescue, and always send a notification inalways
Common Mistakes¶
- Assuming a failure inside
rescue:itself is silently swallowed — it isn't; an unhandled failure there still fails the host. - Forgetting
always:runs even on a host that never enteredrescue:(i.e., theblockfully succeeded) — it isn't only for the failure path.
Interview Questions¶
- What's the difference between
rescue:andalways:? - How would you implement a deployment rollback using
block/rescue?
Next¶
Continue to Error Handling.