ansible - 整个剧本仅运行一次Ansible处理程序

标签 ansible ansible-handlers

我只想在整个剧本中只运行一次处理程序。

我尝试在剧本文件的以下内容中使用include语句,但这导致处理程序多次运行,每次播放一次:

- name: Configure common config
  hosts: all
  become: true
  vars:
        OE: "{{ ansible_hostname[5] }}"
  roles:
    - { role: common }
  handlers:
    - include: handlers/main.yml

- name: Configure metadata config
  hosts: metadata
  become: true
  vars:
        OE: "{{ ansible_hostname[5] }}"
  roles:
    - { role: metadata }
  handlers:
    - include: handlers/main.yml

这是handlers/main.yml的内容:
- name: restart autofs
  service:
    name: autofs.service
    state: restarted

这是通知处理程序的任务之一的示例:
- name: Configure automount - /opt/local/xxx in /etc/auto.direct
  lineinfile:
     dest: /etc/auto.direct
     regexp: "^/opt/local/xxx"
     line: "/opt/local/xxx   -acdirmin=0,acdirmax=0,rdirplus,rw,hard,intr,bg,retry=2  nfs_server:/vol/xxx"
  notify: restart autofs

我如何才能让剧本对整个剧本只执行一次处理程序?

最佳答案

答案

标题中问题的字面回答是:否。

剧本是戏剧的 list 。 Playbook没有 namespace ,没有变量,没有状态。所有配置,逻辑和任务都在游戏中定义。

处理程序是一项具有不同调用时间表的任务(不是顺序的,而是有条件的,在播放结束时一次,或由meta: flush_handlers任务触发)。

处理程序属于剧本,而不是剧本,并且无法在剧本之外(即在剧本的结尾)触发它。

解决方案

不引用处理程序就可以解决问题。

您可以使用 group_by module根据每次播放底部的任务结果创建一个临时组。

然后,您可以在剧本的末尾定义一个单独的剧本,在属于上述临时组的目标上重新启动服务。

请引用下面的 stub 以获取该想法:

- hosts: all
  roles:
    # roles declaration
  tasks:
    - # an example task modifying Nginx configuration
      register: nginx_configuration

    # ... other tasks ...

    - name: the last task in the play
      group_by:
        key: hosts_to_restart_{{ 'nginx' if nginx_configuration is changed else '' }}

# ... other plays ...

- hosts: hosts_to_restart_nginx
  gather_facts: no
  tasks:
    - service:
        name: nginx
        state: restarted

关于ansible - 整个剧本仅运行一次Ansible处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41556574/

相关文章:

ansible - 仅在需要时使用处理程序执行 Ansible 重启

ansible - 在ansible中调用角色时如何使用become?

ansible - 是否可以循环遍历特定主机和配置的数组

json - 在带有 Jmespath 的多选哈希中使用来自 json src 文档的键

docker - 来自 OSX 的 Ansible Docker 模块

linux - 通过一些脚本在多台机器的目录下创建一个文件?

Ansible 处理程序 - 未从救援 block 中调用

使用 group_by 时 Ansible 将看不到处理程序