linux - 如何使用 Ansible 等待服务器重启?

我正在尝试重新启动服务器,然后等待,使用这个:

- name: Restart server
  shell: reboot

- name: Wait for server to restart
  wait_for:
    port=22
    delay=1
    timeout=300

但我收到此错误:

TASK: [iptables | Wait for server to restart] ********************************* 
fatal: [example.com] => failed to transfer file to /root/.ansible/tmp/ansible-tmp-1401138291.69-222045017562709/wait_for:
sftp> put /tmp/tmpApPR8k /root/.ansible/tmp/ansible-tmp-1401138291.69-222045017562709/wait_for

Connected to example.com.
Connection closed

最佳答案

Ansible >= 2.7(2018 年 10 月发布)

使用内置的reboot模块:

- name: Wait for server to restart
  reboot:
    reboot_timeout: 3600

Ansible

作为任务重启

- name: restart server
  shell: 'sleep 1 && shutdown -r now "Reboot triggered by Ansible" && sleep 1'
  async: 1
  poll: 0
  become: true

这会将 shell 命令作为 asynchronous task 运行。 ,所以 Ansible 不会等待命令结束。通常 async 参数为任务提供最大时间,但由于 poll 设置为 0,如果命令完成,Ansible 将永远不会轮询 - 它会使该命令成为“触发和忘记”。 shutdown 之前和之后的 sleep 是为了防止在 Ansible 仍连接到远程主机时在重启期间中断 SSH 连接。

作为任务等待

你可以使用:

- name: Wait for server to restart
  local_action:
    module: wait_for
      host={{ inventory_hostname }}
      port=22
      delay=10
    become: false

..但你可能更喜欢使用 {{ ansible_ssh_host }} 变量作为主机名和/或 {{ ansible_ssh_port }} 作为 SSH 主机和端口,如果你使用如下条目:

hostname         ansible_ssh_host=some.other.name.com ansible_ssh_port=2222 

..在您的库存中(Ansible hosts 文件)。

这将运行 wait_for任务 on the machine running Ansible .此任务将等待远程主机上的 22 端口打开,延迟 10 秒后开始。

作为处理程序重启并等待

但我建议将它们都用作处理程序,而不是任务。

这样做有两个主要原因:

  • 代码重用 - 您可以将处理程序用于许多任务。 示例: 触发服务器重启after changing the timezone并在更改内核后,

  • 仅触发一次 - 如果您将处理程序用于几个任务,并且其中超过 1 个会进行一些更改 => 触发处理程序,那么处理程序所做的事情只会发生一次。 示例:如果您将 httpd 重新启动处理程序附加到 httpd 配置更改和 SSL 证书更新,那么在配置和 SSL 证书更改的情况下,httpd 将仅重新启动一次。

阅读有关处理程序的更多信息 here .

作为处理程序重启并等待重启:

  handlers:

    - name: Restart server
      command: 'sleep 1 && shutdown -r now "Reboot triggered by Ansible" && sleep 1'
      async: 1
      poll: 0
      ignore_errors: true
      become: true

    - name: Wait for server to restart
      local_action:
        module: wait_for
          host={{ inventory_hostname }}
          port=22
          delay=10
        become: false

..并在您的任务中按顺序使用它,就像这样,这里与重新启动服务器处理程序配对:

  tasks:
    - name: Set hostname
        hostname: name=somename
        notify:
          - Restart server
          - Wait for server to restart

请注意 handlers are run in the order they are defined, not the order they are listed in notify !

https://stackoverflow.com/questions/23877781/

相关文章:

linux - 使用 find 列出所有图形图像文件?

python - 如何用python替换像文本一样的sed?

linux - 如何在/etc/fstab 中指定带有空格的标签/路径?

linux - 基于shell中正则表达式的颜色突出显示输出

php - 如何通过 ssh 检查 ubuntu 服务器上是否存在 php 和 apache

linux - 计算一个单词在文件中出现的次数

c - 如何检查存储在变量中的给定文件描述符是否仍然有效?

linux - 如何在 Linux 中查看日志文件并在查看时应用自定义过滤器?

linux - 如何使用 linux shell 脚本删除 ^[ 和文件中的所有转义序列

linux - 我可以使用 awk 将所有小写字母转换为大写吗?