Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a server is reachable from host and has port open with Ansible

Tags:

ansible

I want to test if the host I am provisioning can reach a specific server and connect to a specific TCP port. If it can't the playbook should fail.

How can I do that?

like image 503
Nathan Avatar asked Sep 30 '16 21:09

Nathan


People also ask

How do you test Ansible connectivity?

Testing Connectivity to Nodes To test that Ansible is able to connect and run commands and playbooks on your nodes, you can use the following command: ansible all -m ping.


2 Answers

There is wait_for module for this.
To check that target.host can access remote.host:8080:

- hosts: target.host
  tasks:
    - wait_for: host=remote.host port=8080 timeout=1
    - debug: msg=ok

There are a lot of other examples in the documentation.

like image 134
Konstantin Suvorov Avatar answered Oct 15 '22 12:10

Konstantin Suvorov


Using wait_for is fine, however it requires the service is actually running and gives a reply.

If you just like to check whether the port is open in your firewall, you can use curl.

- name: Check if host is reachable
  shell:
    cmd: "/usr/bin/curl --connect-timeout 10 --silent --show-error remote.host:8080"
    warn: no
    executable: /bin/bash 
  register: res
  failed_when: res.rc in [28] or res.stderr is search("No route to host")

When the port is open but service does not run you get an curl: (7) Failed connect to 10.192.147.224:27019; Connection refused" which you would consider as OK.

A connection blocked by firewall will return curl: (28) Connection timed out after 10001 milliseconds

like image 27
Wernfried Domscheit Avatar answered Oct 15 '22 14:10

Wernfried Domscheit