Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having ansible run a script without the exit code stopping the ssh connection

Tags:

shell

ssh

ansible

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.

like image 708
MilindaD Avatar asked Jun 13 '17 15:06

MilindaD


People also ask

How do I ignore fatal errors in Ansible?

Ignoring failed commands By default Ansible stops executing tasks on a host when a task fails on that host. You can use ignore_errors to continue on in spite of the failure. The ignore_errors directive only works when the task is able to run and returns a value of 'failed'.

How do you handle long running tasks in Ansible?

By default, for Ansible tasks, the connections stay open until the task is done on each node, but this may not be the desired behavior for some functions as sometimes the task can take more time than SSH timeouts. You can run such long running tasks in the background and check their status later.

Does Ansible have a timeout?

Ansible will still block the next task in your playbook, waiting until the async task either completes, fails or times out. However, the task will only time out if it exceeds the timeout limit you set with the async parameter.

Does Ansible SSH for each task?

Enable SSH pipelining It's more of an Ansible feature than an SSH feature. By default, when Ansible uses SSH and SSH-like connection plugins, it will SSH to the target host multiple times for each task.


1 Answers

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.

like image 137
Konstantin Suvorov Avatar answered Oct 17 '22 05:10

Konstantin Suvorov