date: 2020-12-19title: Ansible:wait_for模块 #标题
tags: ansible #标签
categories: ansible # 分类

当你利用service 启动tomcat,或数据库后,他们真的启来了么?这个你是否想确认下?
wait_for模块就是干这个的。等待一个事情发生,然后继续。它可以等待某个端口被占用,然后再做下面的事情,也可以在一定时间超时后做另外的事。

常用参数

参数名 是否必须 默认值 选项 说明
connect_timeout no 5 在下一个事情发生前等待链接的时间,单位是秒
delay no 0 延时,大家都懂,在做下一个事情前延时多少秒
host no 127.0.0.1 执行这个模块的host
exclude_hosts 与state=drained一起使用。用于指定,在寻找活跃的TCP链接的时候,要忽略的主机或IP列表。
path no 当一个文件存在于文件系统中,下一步才继续。
port no 端口号,如8080
search_regex 用于匹配文件或socket链接中的一个字符串。
state no started present/started/stopped/absent/drained 当检查端口的时候,started会确保端口打开;stopped会确保端口关闭;drained会检查活跃的链接。当检查文件或搜索字符串的时候,present和started会确保文件或字符串存在。absent会确保文件不存在或被移除。(Choices: present, started, stopped, absent, drained)[Default: started]

示例

  1. # 10秒后在当前主机开始检查8000端口,直到端口启动后返回
  2. - wait_for: port=8000 delay=10
  3. # 检查path=/tmp/foo直到文件存在后继续
  4. - wait_for: path=/tmp/foo
  5. # 直到/var/lock/file.lock移除后继续
  6. - wait_for: path=/var/lock/file.lock state=absent
  7. # 直到/proc/3466/status移除后继续
  8. - wait_for: path=/proc/3466/status state=absent
  9. # 等待所有本地IP上的8000端口,关闭活跃连接。每10秒检查一次,超时时间是300秒。
  10. - name: wait_for 8080 stop
  11. wait_for:
  12. host: 0.0.0.0
  13. port: 8080
  14. delay: 10
  15. state: drained
  16. # 等待所有IP上的8000端口,关闭活跃连接。每10秒检查一次,超时时间是300秒。
  17. - wait_for: host=0.0.0.0 port=8000 delay=10 state=drained
  18. # 等待所有IP上的8000端口,关闭活跃的连接。忽略来自10.2.1.2和10.2.1.3上的连接。超时时间是300秒。
  19. - wait_for: host=0.0.0.0 port=8000 state=drained exclude_hosts=10.2.1.2,10.2.1.3
  20. # 一直等到/tmp/foo这个文件存在。
  21. - wait_for: path=/tmp/foo
  22. # 一直等到字符串completed出现在文件/tmp/foo中。
  23. - wait_for: path=/tmp/foo search_regex=completed
  24. # 一直等到lock文件被删除。
  25. - wait_for: path=/var/lock/file.lock state=absent
  26. # 一直等到进程结束,并且pid被销毁。
  27. - wait_for: path=/proc/3466/status state=absent
  28. # 等待22端口被打开,并且包含字符串OpenSSH。并且不确保inventory_hostname是可解析的。每10秒检查一次,超时时间是300秒。
  29. - local_action: wait_for port=22 host="{{ ansible_ssh_host | default(inventory_hostname) }}" search_regex=OpenSSH delay=10