我正在使用以下Ansible playbook同时关闭远程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 module,但我不确定这是否是它的真正目的:
- 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"}
答案 0 :(得分:2)
没有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
替换。
答案 1 :(得分:2)
在更受限制的环境中,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