我试图测试一批连接,但是所有错误恢复失败的连接都是“超时”,但是我知道(我测试过)其中一些“没有通往主机的路由”。 如何在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
答案 0 :(得分:0)
引用wait_for
module的文档标题
wait_for –等待条件,然后继续
如果我“改写”您所写的条件,则内容将类似于:“等待主机X成为可解析的目标,并等待在该目标上打开端口22,重试无延迟,并在3s后超时”
这通常是您启动的测试,因为您启动了一个新的虚拟机并将其注册到dns中。因此,您等待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
module:
如果您要检查的主机不满足上述所有条件(例如,即使未安装python,您也希望测试成功),则将需要其他方案。通过ping
模块运行ICMP command
是多种解决方案之一。
答案 1 :(得分:0)
我最终做了这样的事情:
- name: Check if port {{ R_PORT }} is open. If it is, let's fail and investigate manually.
shell: ss -ltpn | grep :{{ R_PORT }} | wc -l
register: open_redis_port
- debug: msg="{{ open_redis_port.stdout }}"
- name: Fail playbook execution if port {{ R_PORT }} is open
fail:
msg: Port {{ R_PORT }} is open. Failing, please investigate manually.
when: open_redis_port.stdout == "2" or open_redis_port.stdout == "1"