我正在使用以下 Ansible 剧本一次性关闭远程 Ubuntu 主机列表:
- hosts: my_hosts
become: yes
remote_user: my_user
tasks:
- name: Confirm shutdown
pause:
prompt: >-
Do you really want to shutdown machine(s) "{{play_hosts}}"? Press
Enter to continue or Ctrl+C, then A, then Enter to abort ...
- name: Cancel existing shutdown calls
command: /sbin/shutdown -c
ignore_errors: yes
- name: Shutdown machine
command: /sbin/shutdown -h now
关于这个问题的两个问题:
- 是否有任何模块可以以比运行两个自定义命令更优雅的方式处理关机?
- 有没有办法检查机器是否真的停机?还是从同一剧本中检查这一点的反模式?
我尝试了net_ping模块,但我不确定这是否是它的真正目的:
- name: Check that machine is down
become: no
net_ping:
dest: "{{ ansible_host }}"
count: 5
state: absent
然而,这失败了
FAILED! => {"changed": false, "msg": "invalid connection specified, expected connection=local, got ssh"}
在更受限制的环境中,在 ping 消息被阻止的情况下,您可以侦听 ssh 端口,直到它关闭。就我而言,我将超时设置为 60 秒。
- name: Save target host IP
set_fact:
target_host: "{{ ansible_host }}"
- name: wait for ssh to stop
wait_for: "port=22 host={{ target_host }} delay=10 state=stopped timeout=60"
delegate_to: 127.0.0.1
没有shutdown
模块。您可以使用单个即发即弃呼叫:
- name: Shutdown server
become: yes
shell: sleep 2 && /sbin/shutdown -c && /sbin/shutdown -h now
async: 1
poll: 0
至于 net_ping
,它适用于交换机和路由器等网络设备。如果您依靠 ICMP 消息来测试关闭过程,则可以使用如下内容:
- name: Store actual host to be used with local_action
set_fact:
original_host: "{{ ansible_host }}"
- name: Wait for ping loss
local_action: shell ping -q -c 1 -W 1 {{ original_host }}
register: res
retries: 5
until: ('100.0% packet loss' in res.stdout)
failed_when: ('100.0% packet loss' not in res.stdout)
changed_when: no
这将等待 100% packet loss
次或在 5 次重试后失败。
在这里,您要使用local_action
因为否则命令将在远程主机上执行(应该关闭(。
并且您希望使用技巧将ansible_host
存储到临时事实中,因为当委派给本地主机时ansible_host
会替换为127.0.0.1
。