我是Ansible的新手,在检查系统是否需要重新启动后尝试操作,这将由ansible本身处理, 我能够确定系统是否需要重新启动,在系统需要一些时间才能正常运行(处于启动状态)后,默认情况下它会执行 5 次 ssh 连接尝试来验证系统是否已启动。 我想补充的一些要点: ansible.config 中 ssh 的默认设置为 5 次尝试,是否可以覆盖 playbook 中的该值。
如果 ssh 尝试保持不变,是否有办法增加重试之间的延迟(例如:5) 我尝试实现相同的目标,但失败了。
- name: Check for require reboot
hosts: "{{ target_host }}"
remote_user: root
gather_facts: False
tasks:
- name: Performing reboot check now after patch integration
command: needs-restarting -r
register: needsrestarting
changed_when:
- needsrestarting.rc != 0
failed_when:
- needsrestarting.rc != 1
- needsrestarting.rc != 0
- name: Reboot the server
tags: reboot
command: reboot
async: 1
poll: 0
# when:
# - needsrestarting.rc == 1
- name: Adding delay for system to come up
wait_for:
timeout: 300
- name: Wait for the nodes to wake up for login with fixed timer
wait_for:
host={{ ansible_ssh_host }}
port={{ ansible_ssh_port }}
timeout=300
state=started
delegate_to= "{{ inventory_hostname }}"
ignore_errors= yes
delay: 60
retries: 20
日志:
UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: OpenSSH_7.4p1, OpenSSL 1.0.2k-fips 26 Jan 2017
最佳答案
您需要将wait_for
任务委托(delegate)给Ansible Controller :
- name: Adding delay for system to come up
wait_for:
timeout: 300
delegate_to: localhost
否则,wait_for
任务将在目标处执行,该目标因重新启动而无法访问。这是一个通用模块,有多种用途。有时远程使用有意义,有时则不然。
相反,人们可能更喜欢在本地执行剧本,最终将任务委派给目标。此决定可能取决于有多少任务要在本地执行以及有多少任务不在本地执行:
- name: Check for require reboot
hosts: "{{ target_host }}"
remote_user: root
gather_facts: False
connection: local
tasks:
...
请注意,本地执行与目标主机、库存等无关,因为它们无论如何都会被迭代。您可以仅通过本地执行来处理整个目标列表(例如 vmWare modules ,在 Controller 上执行并在 list 目标上创建磁盘)。
来自 wait_for
上的 Ansible 文档 module ,对于特定的 ssh 连接,您实际上可以改善等待条件(默认“超时”值为 300 秒):
# Do not assume the inventory_hostname is resolvable and delay 10 seconds at start
- name: Wait 300 seconds for port 22 to become open and contain "OpenSSH"
wait_for:
port: 22
host: '{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}'
search_regex: OpenSSH
delay: 10
connection: local
或者使用特定的wait_for_connection
module为此目的:
# Wake desktops, wait for them to become ready and continue playbook
- hosts: all
gather_facts: no
tasks:
- name: Send magic Wake-On-Lan packet to turn on individual systems
wakeonlan:
mac: '{{ mac }}'
broadcast: 192.168.0.255
delegate_to: localhost
- name: Wait for system to become reachable
wait_for_connection:
- name: Gather facts for first time
setup:
...
注意第一个任务,在本地执行,因为目标尚不可用,但它们是魔术数据包的目的地。
之后,就不需要委派 wait_for_connection
任务,因为它是为这种方式运行而构建的。
关于重新启动后 Ansible ssh 连接超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61384479/