Shared connection to host closed

I have a simple task that runs a bash script. When the script exits with 0, the stderr still contains “Shared connection to host closed.”. This is quite misleading, since there was no actual error.

This is the script:

#!/bin/bash

systemctl is-active nginx

The task:

- name: Check if Nginx service is running
  script: check.sh
  register: s3q2

- debug:
    var: s3q2

- name: Store s3q2 result as a persistent fact
  set_fact:
    s3q2_result:
      exit_code: "{{ s3q2.rc }}"
      additional_data:
        script: "{{ lookup('file', 'check.sh') }}"
        stdout: "{{ s3q2.stdout }}"
        stderr: "{{ s3q2.stderr }}"

How can I prevent stderr containing “Shared connection to … closed.”?

I stop failures from causing tasks to fail like this:

- name: Check if Nginx service is running
  script: check.sh
  register: s3q2
  failed_when: s3q2.rc is not ansible.builtin.regex('^0|1$')

However this might not be the answer to your “Shared connection to host closed.” issue? :woman_shrugging:

1 Like

If the shell script really is just checking the state of a service, you might consider using ansible.builtin.service_facts instead. This uses a builtin module that will already have appropriate fact gathering/setting, as well as failure detection built in.

The examples section shows how to poll a host, and then act on the state of a specific service as needed.

2 Likes

The system service check is just one of the examples. I will need to test a bunch of other things such as if a file was created, if the contents of the file match X, if an endpoint returns a certain value and many more.

It sounds that the “Shared connection to host closed.” really has no workaround.

Usually exit codes (as @Chris suggested) are the way to determine script failure.

If you really need to, then you can supply -o LogLevel=QUIET to the ssh command via ssh_common_args option for the ssh connection plugin (the link lists the ways to configure it).

But this will be thrown out the windows if you ever choose to use -v flag with ansible which also enables ssh verbosity with a lot more messages.

Alternatively you could use copy and command module together to avoid this.

That said, it’s always the best option to existing modules instead of resorting to shell scripts whenever possible.

Here are some examples for the things you listed:

if a file was created

Check stat module, and it’s result.stat.exists return option.

if the contents of the file match X

Check stat module, and it’s result.stat.checksum to compare the content.

if an endpoint returns a certain value

Check uri module


Feel free to ask help for other tasks you need to do! :slight_smile:

4 Likes