我为reboot server
创建了一个处理程序,并且我的角色是使用几种配置来设置操作系统(此角色中约有6个任务),并且仅在以下任何情况下,我想触发reboot server
处理程序整个角色的任务都会更改,整个角色完成后也会更改。
我试图在剧本中添加“ notify”作为角色。但收到错误消息ERROR! 'notify' is not a valid attribute for a Play
site.yml
---
- name: Setup OS parameters
hosts: master_servers
roles:
- os_prep
tags: os_prep
notify:
- restart server
用于重新启动服务器的处理程序
---
- name: restart server
command: /sbin/shutdown -r now
async: 0
poll: 0
ignore_errors: true
notify:
- check server status
- name: check server status
wait_for:
port: 22
host: '{{ inventory_hostname }}'
search_regex: OpenSSH
delay: 10
timeout: 60
connection: local
在运行整个角色“ os_prep”之后,如果角色中的任何任务的状态为“已更改”,则将触发restart server
处理程序。
答案 0 :(得分:1)
notify
是任务的属性,而不是剧本的属性。因此,您应该将notify: restart server
添加到您角色的所有任务中。假设您的所有任务都在roles/os_prep/tasks/main.yml
中。看起来像这样:
---
- name: Configure this
template:
src: myConfig.cfg.j2
dest: /etc/myConfig.cfg
notify: restart server
- name: Change that
moduleX:
…
notify: restart server
- name: Add users
user:
name: "{{ item.key }}"
home: "/home/{{ item.key }}"
uid: "{{ item.value.uid }}"
with_dict: "{{ users }}"
notify: restart server
- …
处理程序的行为将按预期进行。如果其中任何一项任务的状态为changed
,它将在播放结束时运行重新引导(仅一次)。
请注意,根据我的看法,您不应将notify
应用于不需要重启的任务。通常只有很少的东西需要重启服务器。在上面的示例中,添加用户之后不需要重启。在大多数情况下,重新启动服务就足够了。但是,当然,我不知道您的用例。
我看到您链接了处理程序。请注意,您也可以使用处理程序的listen
属性。在执行任务时,您宁愿notify: Restart and wait server
,而您的roles/os_prep/handlers/main.yml
看起来像这样:
---
- name: restart server
command: /sbin/shutdown -r now
async: 0
poll: 0
ignore_errors: true
listen: Restart and wait server
- name: check server status
wait_for:
port: 22
host: '{{ inventory_hostname }}'
search_regex: OpenSSH
delay: 10
timeout: 60
connection: local
listen: Restart and wait server
请注意,您也可以使用reboot
模块来代替command: shutdown -r
。
以下是文档:https://docs.ansible.com/ansible/latest/modules/reboot_module.html