ansible - 运行 仅当角色中的任何任务发生变化时才处理

ansible - run handler only if any task in role changed

我为 reboot server 创建了一个处理程序,我有一个角色可以设置 os 多个配置(这个角色大约有 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' 之后,如果角色中的任何任务具有 'changed' 状态,则 restart server 处理程序将被触发。

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