我曾经拥有简单的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
提前感谢。
答案 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
中定义处理程序。