How to get response of Ansible telnet module

2.8k views Asked by At

Below are couple of IP addresses and their telnet response (output)

telnet 10.9.9.112 22
Trying 10.9.9.112......

telnet 10.9.9.143 22
Trying 10.9.9.143.....
telnet: connect to address 10.9.9.143: Connection refused.

For the first IP 10.9.9.112 there is no connection and firewall blocks any connection from source to destination. The output simply says Trying .... and stays that way without printing anything else.

For the second IP 10.9.9.143 i get Connection refused immediately in the output and the control back to the prompt.

I wish to grab both scenarios in when condition and perform different activities for both the cases.

I tried to use Ansible's telnet module but I don't know how to grab both the different outputs in the registered variable.

In my case it prints the same message for both the IPs.

Ansible output for first ip:

TASK [debug] *************************************
ok: [localhost] => {
   "msg": "HERE:{u'msg': u'Timeout when waiting for 10.9.9.112', u'failed': True, 'changed': False, u'elapsed': 4}"

Ansible Output for second ip:

TASK [debug] *************************************
ok: [localhost] => {
   "msg": "HERE:{u'msg': u'Timeout when waiting for 10.9.9.143', u'failed': True, 'changed': False, u'elapsed': 3}"

The only difference I see is the value for elapsed.

Here is my playbook.

---
- name: "Play 1"
  hosts: localhost
  tasks: 
    - wait_for:
        hosts: "{{ item }}"
        port: 22
        state: started
        delay: 3
        timeout: 90
      ignore_errors: yes
      register: telnetout
      loop:
        - 10.9.9.112
        - 10.9.9.143

    - debug:
        msg: "HERE: {{ telnetout }}"
1

There are 1 answers

0
Ashar On BEST ANSWER

telnet module unfortunately does not record Connection Refused message in the output.

We have to use raw module instead like below.

---
- name: "Play 1"
  hosts: localhost
  tasks: 
    - raw: "timeout --signal=9 2 telnet {{ item }} 22"
      ignore_errors: yes
      register: telnetout
      loop:
        - 10.9.9.112
        - 10.9.9.143

- debug:
    msg: "HERE: {{ telnetout }}"