我正在尝试重新启动服务器,然后等待,使用这个:
- 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
最佳答案
使用内置的reboot模块:
- name: Wait for server to restart
reboot:
reboot_timeout: 3600
- 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/