首页 > 解决方案 > Ansible wait_for 不响应正确错误

问题描述

我试图测试一批连接,但所有错误响应失败的连接都是“超时”,但我知道(我测试过)其中一些是“没有到主机的路由”。我如何在 ansible 中使用 wait_for 来做到这一点?

- name: Test connectivity flow
  wait_for: 
    host: "{{ item.destination_ip }}"
    port: "{{ item.destination_port }}"
    state: started         # Port should be open
    delay: 0               # No wait before first check (sec)
    timeout: 3             # Stop checking after timeout (sec)
  delegate_to: "{{ item.source_ip }}"
  failed_when: false
  register: test_connectivity_flow_result

- name: Append result message to result list msg
  set_fact:
    result_list_msg: "{% if test_connectivity_flow_result.msg is defined %}{{ result_list_msg + [test_connectivity_flow_result.msg] }}{% else %}{{ result_list_msg + [ '' ] }}{% endif %}"

当前响应:等待 1.1.1.1:1040 时超时

预期响应:没有到主机 1.1.1.1:1040 的路由

标签: testingansibleconnectivity

解决方案


引用模块文档的标题wait_for

wait_for – 在继续之前等待条件

如果我“改写”您所写的条件,这将给出如下内容:“等待主机 X 成为可解析的目标并在该目标上打开端口 22,重试没有延迟,并在 3 秒后超时”。

这通常可能是您启动的测试,因为您启动了一个新 vm 并将其注册到 dns.xml 中。因此,您等待 dns 传播并且 ssh 端口可用。

在您的情况下,您会超时,因为您的主机名永远不会成为可解析的地址。

如果您特别想测试没有路由到主机并且不想等到路由最终可用,您需要以其他方式执行此操作。这是一个带有该ping模块的简单示例剧本:

---
- name: Very basic connection test 
  hosts: localhost
  gather_facts: false

  tasks:

    - name: Test if host is reachable (will report no route if so)
      ping:
      delegate_to: nonexistent.host.local

结果是:

PLAY [Very basic connection test] *****************************************************

TASK [Test if host is reachable (will report no route if so)] *************************
fatal: [localhost]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: Could not resolve hostname nonexistent.host.local: Name or service not known", "unreachable": true}

PLAY RECAP ****************************************************************************
localhost                  : ok=0    changed=0    unreachable=1    failed=0    skipped=0    rescued=0    ignored=0

请注意,ping模块

  • 如果是这样,将报告没有路由到主机
  • 将隐式尝试连接到端口 22
  • 将确保主机已安装 python 并准备好通过 ansible 进行管理。

如果您尝试检查的主机不应该满足上述所有条件(例如,即使没有安装python,您也希望测试成功),您将需要其他方案。ping通过模块运行 ICMPcommand是多种解决方案之一。


推荐阅读