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.

Ansible in a Minute — failed_when

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

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: Fail the task only when the command output contains ERROR
  hosts: all
  gather_facts: true
  tasks:
    - name: Run a command and check for ERROR in output
      ansible.builtin.command:
        cmd: /path/to/command
      register: command_output

    - name: Fail task if command output contains ERROR
      ansible.builtin.fail:
        msg: "Command output contains ERROR"
      failed_when: "'ERROR' in command_output.stderr or 'ERROR' in command_output.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.

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 failed_when to control when a task fails · Level Up Labs