Monday, June 8, 2026

Ansible block, rescue, and always

In Ansible, a block logically groups multiple tasks together, allowing you to control execution flow and handle errors as a single unit. The always keyword defines a sequence of tasks within a block that execute regardless of whether the tasks inside the block succeeded or failed.

1. How the block and always Structure Works

This combination is conceptually similar to a try/finally construct in programming languages such as Python and Java.

Execution Flow
  1. block: The primary sequence of tasks you want to execute.
  2. rescue (optional): A sequence of tasks that runs only if a task inside the block fails.
  3. always: A sequence of tasks that runs unconditionally, whether the block succeeds, fails, or is handled by the rescue section.

2. When to Use always

The always section is best suited for guaranteed cleanup operations and state restoration that must occur regardless of playbook execution outcomes.

Common Use Cases
  • Deleting temporary files, scripts, or installer packages.
  • Releasing locks or closing connections.
  • Restoring maintenance windows or re-enabling monitoring alerts.
  • Ensuring specific services are restarted or left in a healthy state.

3. Code Example

The following playbook demonstrates how block, rescue, and always work together:

- hosts: web_servers
  tasks:
    - name: Run main operations with error handling
      block:
        - name: Step 1 - Perform deployment tasks
          ansible.builtin.command: /bin/deploy_app

        - name: Step 2 - Verify application status
          ansible.builtin.command: /bin/verify_app

      rescue:
        - name: Rollback deployment on failure
          ansible.builtin.command: /bin/rollback_deploy

      always:
        - name: Clean up temporary installer files
          ansible.builtin.file:
            path: /tmp/app_installer.tar.gz
            state: absent

        - name: Re-enable monitoring alerts
          ansible.builtin.uri:
            url: https://monitoring.local
            method: POST
In the above code, ansible.builtin.command is a package that runs the script file/executable file specified against it. 

4. Execution Scenarios

Scenario block rescue always
All tasks succeed ✅ Runs ❌ Skipped ✅ Runs
Task fails inside block ❌ Fails ✅ Runs ✅ Runs
Rollback succeeds Completed Completed ✅ Runs

5. Key Takeaway

Think of Ansible's execution flow as:

block → rescue → always
  • block performs the primary work.
  • rescue handles failures and recovery actions.
  • always guarantees cleanup and state restoration.
This pattern is ideal for deployments, upgrades, maintenance operations, and any automation workflow that requires reliable cleanup regardless of success or failure.

No comments:

Post a Comment

Ansible Cheat Sheet

Ansible is an agentless automation platform used for: Server configuration Application deployment Infrastructure provisioning Patc...