What is failed_when for, and when do you need it?
It replaces Ansible's own success test with your condition; the task is marked failed when the condition is true. You need it when a command "succeeds" (exit code 0) but its output reports an error.
* failed_when and changed_when override how Ansible labels a task's result. *
Many scripts print an error and still exit with 0, so Ansible would report them as successful. failed_when looks at the registered result instead:
tasks:
- name: Run user creation script
ansible.builtin.shell: /usr/local/bin/create_users.sh
register: command_result
failed_when: "'Password missing' in command_result.stdout"
If the script's output contains Password missing, the task fails, even with exit code 0.
Note that failed_when replaces the default test rather than adding to it: with the condition above, a non-zero exit code alone would no longer fail the task. To keep both, combine them: failed_when: command_result.rc != 0 or 'Password missing' in command_result.stdout. The opposite case works too: failed_when: command_result.rc not in [0, 1] accepts exit code 1 as a normal answer (as grep uses it for "no match").
Go deeper:
Defining failure (official docs) โ
failed_whenwith output and return codes, and combining conditions.