在安装角色之前如何等待 ssh 在主机上可用?

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

有没有办法在安装角色之前等待 ssh 在主机上可用?有 wait_for_connection 但我只是想出了如何在任务中使用它。

这个特定的剧本在尝试安装角色之前在云提供商上启动服务器。但失败,因为主机上的 ssh 服务尚不可用。

我应该如何解决这个问题?

---
- 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

Ansible 播放操作以 pre_tasks 开头,然后是 roles,然后是 tasks,最后是 post_tasks。将您的 wait_for_connection 任务移至第一个 pre_tasks,它将阻止所有内容,直到连接可用:

- 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: ...

有关执行顺序的更多信息,请参阅 this title in role's documentation(注释上方的段落)。

注意:您可能也想将所有当前示例任务移到该部分,以便在执行任何其他操作之前收集事实并安装 curl。