Ansible wait_for 似乎不起作用

ale*_*exk 5 ansible ansible-2.x

我正在通过 Terraform 配置一个新服务器,并使用 Ansible 作为本地系统上的配置程序。

Terraform 在 EC2 上配置一个系统,然后运行 ​​Ansible playbook,提供新建系统的 IP 作为库存。

我想使用 Ansible 等待系统完成启动并阻止尝试进一步的任务,直到可以建立连接。到目前为止,我一直在使用手动暂停,这是不方便且不精确的。

Ansible 似乎并没有按照文档所说的那样做(除非我错了,这是一种很可能的情况)。这是我的代码:

- name: waiting for server to be alive
    wait_for:
      state: started
      port: 22
      host: "{{ ansible_ssh_host | default(inventory_hostname) }}"
      delay: 10
      timeout: 300
      connect_timeout: 300
      search_regex: OpenSSH
    delegate_to: localhost
Run Code Online (Sandbox Code Playgroud)

此步骤中发生的情况是,连接未等待超过 10 秒就建立连接,并且失败。如果服务器已启动并且我再次尝试剧本,它会正常工作并按预期执行。

我也尝试过do_until样式循环,但似乎永远不起作用。文档中给出的所有示例都使用 shell 输出,并且我看不出它有任何适用于非 shell 模块的方法。

如果我尝试注册结果并使用调试模块将其打印出来,我似乎也无法获得任何调试信息。

有人对我做错了什么有什么建议吗?

tec*_*raf 3

当您使用delegate_toor local_actionmodule 时,{{ ansible_ssh_host }}解析为localhost,因此您的任务始终使用以下参数运行:

host: localhost
Run Code Online (Sandbox Code Playgroud)

它等待 10 秒,检查与本地主机的 SSH 连接并继续(因为很可能它已打开)。


如果您使用gather_facts: false(我相信您这样做),您可以在之前添加一个set_fact任务,将目标主机名值存储在变量中:

- set_fact:
    host_to_wait_for: "{{ ansible_ssh_host | default(inventory_hostname) }}"
Run Code Online (Sandbox Code Playgroud)

并将该行更改为:

host: "{{ host_to_wait_for }}"
Run Code Online (Sandbox Code Playgroud)

您可以使用以下剧本验证测试变量:

---
- hosts: all
  gather_facts: false
  tasks:
    - set_fact:
        host_to_wait_for: "{{ ansible_ssh_host | default(inventory_hostname) }}"
    - debug: msg="ansible_ssh_host={{ ansible_ssh_host }}, inventory_hostname={{ inventory_hostname }}, host_to_wait_for={{ host_to_wait_for }}"
      delegate_to: localhost
Run Code Online (Sandbox Code Playgroud)

或者,您可以尝试找到一种方法,将 EC2 实例的 IP 地址作为变量提供给 Ansible,并将其用作参数值host:。例如,您从 CLI 运行 Ansible,然后传递${aws_instance.example.public_ip}--extra-vars参数。