How to get response of Ansible telnet module

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

telnet 10.9.9.112 22Trying 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.