Quiz Entry - updated: 2026.11.12
What do the block, rescue and always sections each do?
block: the main tasks to run.rescue: runs only if a task inblockfailed, to recover.always: runs afterwards in every case, success or failure.
* rescue is the catch, always is the finally. *
tasks:
- name: Upgrade DB
block:
- name: upgrade the database
ansible.builtin.shell:
cmd: /usr/local/lib/upgrade-database
rescue:
- name: revert the database upgrade
ansible.builtin.shell:
cmd: /usr/local/lib/revert-database
always:
- name: always restart the database
ansible.builtin.service:
name: mariadb
state: restarted
If the upgrade works, rescue is skipped and always restarts the database. If the upgrade fails, Ansible stops the rest of the block, runs rescue to revert, and then runs always. Either way the database comes back up.
This is the same idea as try / catch / finally in programming languages. And like a catch, a successful rescue counts as handled: the host stays in the play and continues with the next task after the block (the failure still shows as rescued=1 in the recap). If a task in rescue fails too, the host fails as usual.
Go deeper:
Handling errors with blocks (official docs) — rescue and always, plus the
ansible_failed_task/ansible_failed_resultvariables available in rescue.Exception handling (Wikipedia) — try/catch/finally, the model blocks follow.