BacklogZero®

Ansible in a Minute · Ansible Core ·

Use failed_when to control when a task fails

Short answer

Use failed_when to decide failure from the registered result instead of the default return code alone.

Request

fail the task only when the command output contains ERROR

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: Demonstrate failed_when
  hosts: localhost
  gather_facts: false
  connection: local

  tasks:
    - name: Run a command and register output
      ansible.builtin.command:
        cmd: echo "status=ok"
      register: cmd_result
      changed_when: false
      failed_when: "'ERROR' in cmd_result.stdout"

How it works

Ansible marks a task as failed when failed_when evaluates to true. Use this when a non-zero return code is not the correct failure signal.

When to use it

  • Parsing CLI tools that return zero on soft errors
  • Failing when expected text is missing

Requirements

  • Ansible: >=2.14

Validation

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

Notes

Combine register with failed_when. Keep the condition explicit. Avoid ambiguous pronouns in the expression.

Try it with BacklogZero

Ask BacklogZero to generate this automation for your environment.

Get BacklogZero today

Related guides

Back to Ansible in a Minute

Use failed_when to control when a task fails · Level Up Labs