ansible

Wait for port to go down on remote host, then come back up, with ansible


I run a script (opnsense install) on a host with Ansible. I'd like to wait for the ssh service to become unreachable (indicating that opnsense has reboot the host), then become available again (indicating the host is back up). The second part is easy, the first part isn't working. Here's one thing I've tried:

- name: Wait for ssh to stop listening
  wait_for:
    host: '{{ ansible_host }}'
    port: '{{ port_ssh }}'
    connect_timeout: 5
    delay: 10
  delegate_to: localhost
  register: result
  retries: 30
  until: result is failed

What is a clean way to wait for ssh stop stop listening, or otherwise be sure the host is down before coming up? I don't want to manually reboot since the opnsense install script does that when it's finished.


Solution

  • Wait for sshd (port 22) to stop. Set the timeout to your needs

            - name: Wait for sshd to stop
              wait_for:
                port: 22
                state: stopped
                timeout: 30
    

    Then, wait for sshd to restart

            - name: Wait for sshd to start again
              wait_for:
                port: 22
                timeout: 30
    

    Put the tasks into a block. In the rescue section display what went wrong.


    Example of a complete playbook for testing

    - hosts: test_23
    
      tasks:
    
        - debug:
            msg: Run a script
    
        - block:
    
            - name: Wait for sshd to stop
              wait_for:
                port: 22
                state: stopped
                timeout: 30
    
            - name: Wait for sshd to start again
              wait_for:
                port: 22
                timeout: 30
    
          rescue:
    
            - debug:
                msg: |
                  {{ ansible_failed_task }}
                  {{ ansible_failed_result }}
    
        - debug:
            msg: Play continues...