I found this to be helpful:
https://medium.com/opsops/anternative-way-to-handle-errors-in-ansible-245a066c340
In your task you want to register the task.
register: some_name
Then add ignore_errors: yes
Then use set_fact
to get each register attribute:
- set_fact:
success: '{{ not([e1, e2]|map(attribute="failed")|max) }}'
Then place this at the end of your block:
- name: Fail server build
command: >
bash scripts/test_file.sh
when: success == false
ignore_errors: yes
The block above would only be executed when success is false
. The key is using ignore_errors
and making a register. From the link I posted and from my testing the task attribute is registered if it fails or not.
Example output:
PLAY [localhost] ***********************************************************************************************
TASK [Gathering Facts] *****************************************************************************************
ok: [localhost]
TASK [Task 1 test] *********************************************************************************************
fatal: [localhost]: FAILED! => {"changed": true, "cmd": ["bash", "scripts/unknown_file.sh"], "delta": "0:00:00.004343", "end": "2021-10-20 14:20:59.320389", "msg": "non-zero return code", "rc": 127, "start": "2021-10-20 14:20:59.316046", "stderr": "bash: scripts/unknown_file.sh: No such file or directory", "stderr_lines": ["bash: scripts/unknown_file.sh: No such file or directory"], "stdout": "", "stdout_lines": []}
...ignoring
TASK [Task 2 test] *********************************************************************************************
changed: [localhost]
TASK [set_fact] ************************************************************************************************
ok: [localhost]
TASK [Fail server build] ***************************************************************************************
changed: [localhost]
TASK [debug] ***************************************************************************************************
ok: [localhost] => {
"success": false
}
PLAY RECAP *****************************************************************************************************
localhost : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1