Ansible wait_for似乎不起作用

时间:2016-08-22 23:22:04

标签: ansible ansible-playbook ansible-2.x

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

Terraform在EC2上配置系统,然后运行Ansible手册,提供新建系统的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

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

我也尝试了do_until样式循环,它似乎永远不会起作用。文档中给出的所有示例都使用shell输出,我看不出它对任何非shell模块都有用。

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

任何人都对我做错了什么有任何建议?

2 个答案:

答案 0 :(得分:1)

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

host: localhost

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

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

- set_fact:
    host_to_wait_for: "{{ ansible_ssh_host | default(inventory_hostname) }}"

并将该行更改为:

host: "{{ host_to_wait_for }}"

您可以使用以下剧本对变量进行校对测试:

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

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

答案 1 :(得分:0)

正如techraf指出的那样,您的库存查找实际上是因为委托而占用了本地主机地址,所以它没有针对正确的机器运行。

我认为你最好的解决方案可能是让terraform将变量传递给包含实例IP地址的playbook。例如:

terraform传递-e "new_ec2_host=<IP_ADDR>"

Ansible任务:

- name: waiting for server to be alive
    wait_for:
      state: started
      port: 22
      host: "{{ new_ec2_host }}"
      delay: 10
      timeout: 300
      connect_timeout: 300
      search_regex: OpenSSH
    delegate_to: localhost
相关问题