Evaluating return code in ansible conditional - Stack Overflow
Handling exit codes from shell?
# exitcode.yml
---
- name: Return code test
hosts: localhost
gather_facts: no
tasks:
- shell: "{{ cmd }}"
ignore_errors: true
register: cmd_out
- debug:
msg: "Return code is 100"
when: cmd_out.rc == 100
ansible-playbook ./exitcode.yml -e "cmd=ls"
Documented here
More on reddit.combash - Capture Return Code of task as exit code for Ansible Playbook - Stack Overflow
Ansible return code ok or ko - Ansible Project - Ansible
hi guys, i've been trying the register the return code in many ways ,
but without any success
appreciate your help
I'm running a yum command using "shell" (I don't want to use the yum module since it lacks most of the features I need). Yum will return 0,1 or 100 as exit code..
How can I work with exit code 100 specifically? For instance, this handles success:
when: yadacommand_result|succeeded
and failed with:
when: yadacommand_result|failed
I want to use "when:" with exit code 100, is this possible or can I only catch success/failure?
# exitcode.yml
---
- name: Return code test
hosts: localhost
gather_facts: no
tasks:
- shell: "{{ cmd }}"
ignore_errors: true
register: cmd_out
- debug:
msg: "Return code is 100"
when: cmd_out.rc == 100
ansible-playbook ./exitcode.yml -e "cmd=ls"
Documented here
Few days ago I wrote blog post about it. probably there is your answer. Dont forget to check additional links at below http://en.enisozgen.com/ansible-working-with-return-codes/
Q: "Is any way to have the return code of the task as the exit code of the AnsiblePlaybook?"
A: There is no such option. It's possible to use ansible-runner instead. See Artifacts.
Use set_stats to customize the playbook's output.
Use ansible-runner to run the playbook.
Get the customized output from artifacts/ID/stdout.
Create wrapper. FWIW, see as a hint arwrapper.bash and Ansible Runner Usage Examples.
ansible-runner is complex and doesn't work on macOS.
Here is the end of my playbook.yml:
tasks:
- name: Prepare VM
script: ./logic.bash &> ~/logic.bash.log
register: returned
ignore_errors: yes
- name: read log
shell: |
cat ~/logic.bash.log
register: file_content
- name: print log
debug:
verbosity: 2
msg: "{{ file_content.stdout }}"
- name: print RC
debug:
msg: "RETURN_CODE: {{returned.rc}}"
And here is the code I use in a script called run.bash to execute the playbook and check the RC of the task.
ID="${RANDOM}"
ansible-playbook -vvvv -i ${BUZYFORM_INVENTORY_FILE} playbook.yml > /tmp/"${ID}"
RC="$(grep RETURN_CODE /tmp/${ID} | cut -d"|" -f2)"
cat /tmp/"${ID}"
[[ ${RC} -gt 0 ]] && exit ${RC} || true