Max Nicholson
Max Nicholson

Reputation: 131

Capture Return Code of task as exit code for Ansible Playbook

Let's start from the very beginning:

I know Ansible has the following exit codes:

*0* -- OK or no hosts matched

*1* -- Error

*2* -- One or more hosts failed

*3* -- One or more hosts were unreachable

*4* -- Parser error

*5* -- Bad or incomplete options

*99* -- User interrupted execution

*250* -- Unexpected error

So the question is if there is any way to have the return code of the task as the exit code of the Ansible Playbook.

Regards,

Upvotes: 3

Views: 12578

Answers (2)

NorseGaud
NorseGaud

Reputation: 781

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

Upvotes: 0

Vladimir Botka
Vladimir Botka

Reputation: 68344

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.

Upvotes: 3

Related Questions