The Block/Rescue/Always structure provides the most robust and controlled way to handle failures in Ansible, often referred to as a "try/catch/finally" mechanism.
✅ Basic Example: Block / Rescue / Always
- name: Demonstrate block, rescue, always
hosts: all
tasks:
- block:
- name: Try to run a command that fails
ansible.builtin.command: /bin/false # This always fails
- name: This will not run
ansible.builtin.debug:
msg: "This won't run because previous task failed."
rescue:
- name: Run when block fails
ansible.builtin.debug:
msg: "Block failed! Running rescue section."
always:
- name: Run always
ansible.builtin.debug:
msg: "This task runs whether block fails or not."
How it works.1️⃣ block:
Contains tasks that you expect might fail.
If all tasks succeed → rescue is not triggered.
If any task fails → rescue is triggered.
2️⃣ rescue:
Runs only if block fails.
Used for:
cleanup
alternative action
error logging
fallback/rollback operations
3️⃣ always:
Runs every time, whether success or failure.
Used for:
closing connections
cleanup
notifications
reporting
block / rescue is used when a task may fail and you want to execute alternative logic in response to that failure.
This pattern is also commonly used to attempt a change inside the block, and if the change fails, automatically
run rollback or recovery actions in the rescue section.
No comments:
Post a Comment