Jack
Jack

Reputation: 1372

Ansible: wait for ssh to be accessible

I want to wait for ssh is accessible before I run task/roles or gather facts, currently I have something like this

- hosts: app
  become: true
  become_user: root
  pre_tasks:
  - name: Wait 300 seconds for port 22 to become open and contain "OpenSSH"
    wait_for:
      port: 22
      host: '{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}'
      search_regex: OpenSSH
      delay: 10
    connection: local
  gather_facts: yes 

but my pre task runs after gather fact task complete, so playbook get failed. is there anyway to check ssh accessibility before gathering facts?

Upvotes: 1

Views: 1416

Answers (1)

George Shuklin
George Shuklin

Reputation: 7877

You need to disable gather_facts and use setup module.

- hosts: app
  become: true
  gather_facts: false
  become_user: root
  pre_tasks:
  - name: Wait 300 seconds for port 22 to become open and contain "OpenSSH"
    wait_for:
      port: 22
      host: '{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}'
      search_regex: OpenSSH
      delay: 10
    connection: local
  - setup:

See setup module docs https://docs.ansible.com/ansible/latest/modules/setup_module.html

Update:

Actually, I would say you don't need to wait for port.

Just retry setup until it succeed.

 - hosts: app
   become: true
   gather_facts: false
   pre_tasks:
     - setup:
       register: setup_status
       until: setup_status is success
       delay: 10
       retries: 30

Upvotes: 4

Related Questions