BacklogZero®

Ansible in a Minute · Ansible Core ·

Use block rescue always to handle a failed task

Short answer

Use block, rescue, and always to recover from a failed task and still run cleanup.

Ansible in a Minute — block rescue always

Subscribe for updates

Get an email whenever we publish new guides and blog posts. Unsubscribe anytime.

By subscribing you agree we may email you about Ansible in a Minute and related Level Up Labs updates. We store your address in the same lead sheet as our contact form.

Request

attempt a command, recover in rescue, and always print a status message using /bin/false

Example

A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.

YAML
---
- name: Handle a failed task with block rescue always
  hosts: all
  gather_facts: true
  tasks:
    - name: Attempt a command and recover on failure
      block:
        - name: Run a command that may fail
          ansible.builtin.command:
            cmd: /bin/false
      rescue:
        - name: Report the failure
          ansible.builtin.debug:
            msg: "Command failed; continuing in rescue"
      always:
        - name: Print status after the attempt
          ansible.builtin.debug:
            msg: "always block ran"

How it works

Tasks in block run first. If a task in block fails, Ansible runs rescue. Tasks in always run whether the block succeeded or failed.

When to use it

  • Recovering from a soft failure without stopping the play
  • Guaranteeing cleanup or status logging after an attempt

Requirements

  • Ansible: >=2.14

Validation

  • Syntax validated
  • Not execution-tested
  • Last verified 2026-09-05

Notes

Use failed_when when you must redefine failure for one task. Use block/rescue/always when you need recovery and cleanup around a group of tasks.

Reference

Built for every Ansible use case in every organization

BacklogZero can generate this kind of automation in your environment, just like it did here.

Get BacklogZero today →

Related guides

← Back to Ansible in a Minute

Use block rescue always to handle a failed task · Level Up Labs