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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With