How to wait for ssh to become available on a host before installing a role?

1k Views Asked by At

Is there a way to wait for ssh to become available on a host before installing a role? There's wait_for_connection but I only figured out how to use it with tasks.

This particular playbook spin up servers on a cloud provider before attempting to install roles. But fails since the ssh service on the hosts isn't available yet.

How should I fix this?

---
- hosts: localhost
  connection: local
  tasks:
    - name: Deploy vultr servers
      include_tasks: create_vultr_server.yml
      loop: "{{ groups['vultr_servers'] }}"

- hosts: all
  gather_facts: no

  become: true

  tasks:
    - name: wait_for_connection # This one works
      wait_for_connection:
        delay: 5
        timeout: 600

    - name: Gather facts for first time
      setup:

    - name: Install curl
      package:
        name: "curl"
        state: present

  roles: # How to NOT install roles UNLESS the current host is available ?
    - role: apache2
      vars:
        doc_root: /var/www/example
        message: 'Hello world!'
    - common-tools
1

There are 1 best solutions below

0
On BEST ANSWER

Ansible play actions start with pre_tasks, then roles, followed by tasks and finally post_tasks. Move your wait_for_connection task as the first pre_tasks and it will block everything until connection is available:

- hosts: all
  gather_facts: no

  become: true
  
  pre_tasks:
    - name: wait_for_connection # This one works
      wait_for_connection:
        delay: 5
        timeout: 600
  
  roles: ...
  
  tasks: ...

For more info on execution order, see this title in role's documentation (paragraph just above the notes).

Note: you probably want to move all your current example tasks in that section too so that facts are gathered and curl installed prior to do anything else.