Saturday, 13 December 2025

Ansible 23. error handling Block/Rescue/Always

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

Building a Safer PostgreSQL CI/CD Pipeline with GitHub Actions: Dev → PR Review → Test Promotion

In my previous post, we explored a simple push-to-main deployment strategy . While functional, that model is not considered an industry best...