2016-12-21 60 views
2

我曾經在我的所有機器上運行簡單的操作手冊(something like this)(RH &基於Debian)來更新它們,並且對於每臺已更新的機器運行腳本(通知處理程序)。Ansible在使用group_by時看不到處理程序

最近,我試圖測試一個名爲group_by新的模塊,所以不是使用when條件運行yum updateansible_distribution == "CentOS",我會第一時間收集的事實和組基於有ansible_pkg_mgr爲重點,然後我一直在尋找運行主機百勝在所有主機上更新,其中的關鍵是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 

提前致謝。

回答

2

您只在其中一個劇本中定義了處理程序。如果你看看縮進,這很清楚。

您爲PackageManager_apt執行的遊戲根本沒有handlers(它無法訪問單獨遊戲中定義的updateX處理程序),因此Ansible抱怨。

如果你不想重複的代碼,你可以保存處理程序,以一個單獨的文件(讓我們將其命名爲handlers.yml),幷包括在兩戲劇有:

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

注:有Handlers: Running Operations On Change關於包含處理程序的部分的註釋:

您無法通知在include內定義的處理程序。從Ansible 2.1開始,這確實起作用,但是包含必須是靜態的。


最後,你應該考慮,而你的劇本轉換爲一個角色。

的常用方法使用的文件名與在其名稱中的架構,以達到你想要的是包括任務(在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定義。

+0

感謝您的提示。 – Rabin