6

We have an ansible task which looks like the following

- name: Check if that created
  script: verification.sh
  register: verification
  changed_when: verification.rc == 1

The above task runs a script which returns an exit signal if failed or success. An example part would be

    if [[ "$item" == "$name" ]]; then
        printf "TEST"
        exit 1
    fi

Where the issue is that when an exit signal other than 0 value is returned the ssh in ansible seems to terminate and gives the error as

TASK [Test Task] ******************
fatal: [default]: FAILED! => {"changed": true, "failed": true, "rc": 1, "stderr": "Shared connection to 127.0.0.1 closed.\r\n", "stdout": "TEST", "stdout_lines": ["TEST"]}

However this works when we return an exit signal of 0 here in the script

I am guessing this is because "exit" is run on the remote host and it then terminates the ssh connection.

How would we bypass this and have the exit signal returned without the error coming.

MilindaD
  • 7,533
  • 9
  • 43
  • 63

3 Answers3

9

You can use failed_when to control what defines failure:

- name: Check if that created
  script: verification.sh
  register: verification
  changed_when: verification.rc == 1
  failed_when: verification.rc not in [0,1]

This will give a failure when exit code is neither 0 nor 1.

michael_bitard
  • 3,613
  • 1
  • 24
  • 35
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
2

Generally playbooks will stop executing any more steps on a host that has a task fail. Sometimes, though, you want to continue on. To do so, write a task that looks like this:

http://docs.ansible.com/ansible/playbooks_error_handling.html#ignoring-failed-commandsIgnoring Failed Commands

- name: Check if that created
  script: verification.sh
  register: verification
  changed_when: verification.rc == 1
  ignore_errors: yes
Berlin
  • 1,456
  • 1
  • 21
  • 43
0

I think this answer is the way: https://stackoverflow.com/a/44538536/2909072

But in my case I do something like (in my script.sh):

# error handle inside a class (function)
if [ "${script_mail_status}" = "Error" ]; then
    echo "Error, check email/log for details. Bye!"
    # Fail the script and playbook
    exit 2
fi

# end of script (EOF), bye!
exit 0

Note: At my company, scripts exit 0 it’s "successful" and 1 it's "successful with errors" and 2 is "error/critical".

In my case, the playbook I will try can be like:

- name: Check if that created
  script: script.sh
  register: result
  changed_when: result.rc in [0,1]
  failed_when: result.rc not in [0,1]

Checking if this works…

JuanRios
  • 37
  • 2