Can't run openssl command with shell module in Ansible

Viewed 1218

I'm trying to run this command using Ansible's shell module:

openssl s_client -connect router1.lab.net:50051

My Ansible play looks like this:

---
- hosts: lab
  connection: local
  tasks:
    - name: Check cert with OpenSSL
      shell: |
        openssl s_client -connect {{ ansible_host }}:50051
      register: cert
      ignore_errors: yes
    - name: Print cert data
      debug:
        msg: "{{ cert }}"
      when: cert is succeeded

When I run the playbook with -vvv I get the following error:

 "stderr": "139631224861120:error:0200206F:system library:connect:Connection refused:../crypto/bio/b_sock2.c:110:\n139631224861120:error:2008A067:BIO routines:BIO_connect:connect error:../crypto/bio/b_sock2.c:111:\nconnect:errno=111",
    "stderr_lines": [
        "139631224861120:error:0200206F:system library:connect:Connection refused:../crypto/bio/b_sock2.c:110:",
        "139631224861120:error:2008A067:BIO routines:BIO_connect:connect error:../crypto/bio/b_sock2.c:111:",
        "connect:errno=111"
    ]

The same openssl command works when I run it from Linux command line and gives the proper output. I tried installing ansible-galaxy collection install community.crypto (https://ansible.fontein.de/collections/community/crypto/x509_certificate_pipe_module.html) but that didn't help.

1 Answers

Your problem is the {{ ansible_host }}. It is an ansible variable, that you can set to tell ansible the IP or hostname of the host to connect to.
In your case, it is probably local as you are using a local-connection.
That is probably why you get a "Connection refused".

Use localhost to connect to the local machine, or an IP or resolvable hostname to connect to a remote host.
You can also try to use {{ ansible_hostname }} if you are connecting to the local host and the hostname is resolvable.

Be aware, that those values of those variables depend the host the task is currently running on.

Check out the list of special variables.

Edit 1:

I realized, what you are trying to do, just now.
Use the get_certificate module to fetch the certificate from a host. Using openssl in shell to do that is really bad practice, as pointed out by Zeitounator. You will need to use the correct host as described above.

Related