用于检查主机在关机后是否真的离线的 Ansible 任务

Dir*_*irk 3 shutdown ansible ansible-2.x

我正在使用以下 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
Run Code Online (Sandbox Code Playgroud)

关于这个的两个问题:

  1. 是否有任何可用的模块可以以比运行两个自定义命令更优雅的方式处理关机?
  2. 有什么方法可以检查机器是否真的停机?还是从同一个剧本中检查它是一种反模式?

我尝试了net_ping 模块,但我不确定这是否是它的真正目的:

- name: Check that machine is down
      become: no
      net_ping:
        dest: "{{ ansible_host }}"
        count: 5
        state: absent
Run Code Online (Sandbox Code Playgroud)

然而,这失败了

FAILED! => {"changed": false, "msg": "invalid connection specified, expected connection=local, got ssh"}
Run Code Online (Sandbox Code Playgroud)

小智 5

在更受限制的环境中,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
Run Code Online (Sandbox Code Playgroud)