Max Allan
Max Allan

Reputation: 959

How to make ansible wait for a port to be ready?

I intended to wait for a port to be ready so used "wait_for"

- name: Wait for service to be ready
  wait_for:
    host: 192.168.1.70
    port: 8080

However it only waits for 300 seconds and then fails.

TASK [Wait for service to be ready] 
fatal: [localhost]: FAILED! => {"changed": false, "elapsed": 300, "msg": "Timeout when waiting for 192.168.1.70:8080"}

So, I added an "until" :

- name: Wait for service to be ready
  wait_for:
    host: 192.168.1.70
    port: 8080
  register: port8080
  until: port8080.failed == "false"

Instead, I get an error :

TASK [Wait for ssh to be ready] 
fatal: [localhost]: FAILED! => {"msg": "The conditional check 'port8080.failed == \"false\"' failed. The error was: error while evaluating conditional (port8080.failed == \"false\"): 'dict object' has no attribute 'failed'"}

BUT if I remove the "until" and add a debug statement, I can see that port8080.failed is set to either true or false as expected.

TASK [debug] ****************************************************************************************************************************
ok: [localhost] => {
  "port8080": {
     "changed": false, 
     "elapsed": 0, 
     "failed": false, 

First question : Is this an ansible bug or am I doing something wrong?
Second question : How can I make my script wait for a connection (for longer than 300 seconds)?

(NB I am actually waiting for a database to start, 300 seconds is too short a time for the DB to start. BUT I don't want to wait for 300 seconds, in case I'm re-running the script and the DB is already running.)

Upvotes: 9

Views: 12851

Answers (1)

nbari
nbari

Reputation: 26925

Give a try to wait_for_connection for example this will work when you reboot your system and want to wait until is reachable/usable:

- name: Something that may reboot
  shell: echo "true"
  register: should_reboot

- name: Rebooting ...
  shell: sleep 2 && /sbin/shutdown -r now "Reboot required"
  async: 1
  poll: 0
  ignore_errors: true
  register: rebooting
  when: should_reboot.stdout == "true"

- name: Wait for rebooted servers to come back
  wait_for_connection:
    connect_timeout: 20
    sleep: 5
    delay: 5
    timeout: 60
  when: rebooting|changed

For checking/testing if a remote host is up this may work:

- name: Wait for service to be ready
  wait_for:
    port: 8080
    host: 127.0.0.1
    connect_timeout: 3
    delay: 3
    timeout: 30

For testing I created a local port 8080 using netcat, for example:

nc -l 8080

if the port is not open you will get something like:

fatal: [localhost]: FAILED! => {"changed": false, "elapsed": 30, "msg": "Timeout when waiting for localhost:8080"}

When the port is open you run the playybook will notice that one connected it will also exit, in case you want to keep it permanent use something like:

nc -kl 8080

Upvotes: 6

Related Questions