Ansible - Resolve "non-zero return code"
by
Jeremy Canfield |
Updated: July 22 2021
| Ansible articles
non-zero return code is displayed when using the shell module and the return code is something other than 0. For example, the following shell command will almost always have a return code of 1.
---
- hosts: all
tasks:
- name: ps command
shell: ps | grep foo
Running this playbook will return the following.
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 not 0 or 1.
---
- hosts: all
tasks:
- name: ps command
shell: ps | grep foo
register: ps
failed_when: ps.rc not in [ 0, 1 ]
...
Or the ignore_errors parameter can be used.
---
- hosts: all
tasks:
- name: ps command
shell: ps | grep foo
ignore_errors: true
...
Or the meta: clear_host_errors module can be used.
---
- hosts: all
tasks:
- name: ps command
shell: ps | grep foo
- meta: clear_host_error
...
Did you find this article helpful?
If so, consider buying me a coffee over at