Let's say you have a playbook that uses the register module to capture the stdout, stderr, and rc (return code) of a command. In this example, the stdout, stderr, and rc of the ps command will be stored in the "out" variable.
---
- hosts: all
tasks:
- name: ps command
shell: ps | grep foo
register: out
- name: standard out
debug:
var: out.stdout_lines
- name: standard error
debug:
var: out.stderr_lines
- name: return code
debug:
var: out.rc
Running this playbook will return the following. Notice the standard out, standard error, and return code tasks were not run, due to a fatal error. This occurred because the return code of the ps command was 1.
PLAY [all]
TASK [Gathering Facts]
ok: [server1.example.com]
TASK [ps command]
fatal: [server1.example.com]: FAILED! => {"changed": true, "cmd": "ps | grep foo", "delta": "0:00:00.021343", "end": "2020-03-13 21:52:36.185781", "msg": "non-zero return code", "rc": 1, "start": "2020-03-13 21:52:36.164438", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
PLAY RECAP
server1.example.com : ok=1 Â changed=0 Â unreacable=0 Â failed=1
Since a return code of 0 and 1 are ok with the ps command, the failed_when parameter can be used to fail when the rc (return code) is greater than or equal to 2, like this.
---
- hosts: all
tasks:
- name: ps command
shell: ps | grep foo
register: ps
failed_when: ps.rc >= 2
- name: standard out
debug:
var: out.stdout_lines
- name: standard error
debug:
var: out.stderr_lines
- name: return code
debug:
var: out.rc
Or like this.
failed_when: ps.rc not in [ 0, 1 ]
Now the play will go through all the tasks.
PLAY [all]
TASK [Gathering Facts]
ok: [server1.example.com]
TASK [ps command]
ok: [server1.example.com]
TASK [standard out]
ok: [server1.example.com] => {
"msg": ""
}
TASK [standard error]
ok: [server1.example.com] => {
"msg": ""
}
TASK [return code]
ok: [server1.example.com] => {
"msg": "1"
}
PLAY RECAP
server1.example.com : ok=1 changed=0 unreacable=0 failed=0