ansible-仅当角色中的任何任务更改时才运行处理程序

时间:2019-08-18 06:34:16

标签: ansible yaml handler roles

我为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处理程序。

1 个答案:

答案 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应用于不需要重启的任务。通常只有很少的东西需要重启服务器。在上面的示例中,添加用户之后不需要重启。在大多数情况下,重新启动服务就足够了。但是,当然,我不知道您的用例。


其他评论

注释1

我看到您链接了处理程序。请注意,您也可以使用处理程序的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

注释2

请注意,您也可以使用reboot模块来代替command: shutdown -r

以下是文档:https://docs.ansible.com/ansible/latest/modules/reboot_module.html