首页 > 解决方案 > 如何在安装角色之前等待 ssh 在主机上可用?

问题描述

有没有办法在安装角色之前等待主机上的 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

标签: ansibleansible-role

解决方案


Ansible 播放动作从pre_tasks, then开始,然后rolestasksfinally 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: ...

有关执行顺序的更多信息,请参阅角色文档中的此标题(注释上方的段落)。

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


推荐阅读