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

时间:2016-12-21 11:27:33

标签: ansible ansible-2.x ansible-handlers

我曾经拥有简单的playbook(something like this),我在我的机器上运行(RH& Debian)来更新它们,并且对于每个更新的机器都运行一个脚本(通知处理程序)。

最近我尝试测试一个名为group_by的新模块,因此在when时使用yum update条件运行ansible_distribution == "CentOS",我将首先收集事实和组主机基于ansible_pkg_mgr作为密钥,然后我想在所有主机上运行yum update,其密钥是PackageManager_yum,请参阅剧本示例:

---
- hosts: all
  gather_facts: false
  remote_user: root
  tasks:

    - name: Gathering facts
      setup:

    - name: Create a group of all hosts by operating system
      group_by: key=PackageManager_{{ansible_pkg_mgr}}

- hosts: PackageManager_apt
  gather_facts: false
  tasks:
    - name: Update DEB Family
      apt: 
        upgrade=dist
        autoremove=yes
        install_recommends=no
        update_cache=yes
      when: ansible_os_family == "Debian"
      register: update_status
      notify: updateX
      tags: 
        - deb
        - apt_update
        - update

- hosts: PackageManager_yum
  gather_facts: false
  tasks:
    - name: Update RPM Family
      yum: name=* state=latest
      when: ansible_os_family == "RedHat"
      register: update_status
      notify: updateX
      tags: 
        - rpm
        - yum
        - yum_update

  handlers:
    - name: updateX
      command: /usr/local/bin/update

这是我收到的错误消息,

PLAY [all] ********************************************************************

TASK [Gathering facts] *********************************************************
Wednesday 21 December 2016  11:26:17 +0200 (0:00:00.031)       0:00:00.031 **** 
....

TASK [Create a group of all hosts by operating system] *************************
Wednesday 21 December 2016  11:26:26 +0200 (0:00:01.443)       0:00:09.242 **** 

TASK [Update DEB Family] *******************************************************
Wednesday 21 December 2016  11:26:26 +0200 (0:00:00.211)       0:00:09.454 **** 
ERROR! The requested handler 'updateX' was not found in either the main handlers list nor in the listening handlers list

提前感谢。

1 个答案:

答案 0 :(得分:2)

您仅在某个播放中定义了处理程序。如果你看一下缩进,那就很清楚了。

您为PackageManager_apt执行的游戏根本没有handlers(它无法访问单独播放中定义的updateX处理程序),因此Ansible会抱怨。< / p>

如果您不想复制代码,可以将处理程序保存到单独的文件中(让我们将其命名为handlers.yml)并在两个播放中包含:

  handlers:
    - name: Include common handlers
      include: handlers.yml

注意:Handlers: Running Operations On Change部分中有关于包含处理程序的注释:

  

您无法通知在include中定义的处理程序。从Ansible 2.1开始,这确实有效,但是include必须是静态的。

最后,您应该考虑将您的剧本转换为角色。

实现目标的常用方法是使用名称中包含体系结构的文件名包含任务(在tasks/main.yml中):

- include: "{{ architecture_specific_tasks_file }}"
  with_first_found:
    - "tasks-for-{{ ansible_distribution }}.yml"
    - "tasks-for-{{ ansible_os_family }}.yml"
  loop_control:
    loop_var: architecture_specific_tasks_file

然后在handlers/main.yml中定义处理程序。