簡體   English   中英

在回調插件中使用“ set_fact”獲取事實集的值

[英]Get value of a fact set with 'set_fact' inside a callback plugin

Ansible 2.3

我有一個回調插件,當劇本完成時會通知外部服務。 在播放期間,此回調插件會收集不同的信息,例如播放變量和錯誤消息,這些信息與HTTP請求一起發送。 例:

{
    "status": 1, 
    "activity": 270,
    "error": "Task xyz failed with message: failure message",
    "files": [ "a.txt", "b.cfg" ]
}

這些信息中的一部分來自在播放過程中設置的變量,可能與該播放有關,包括文件的路徑,更改的資源列表等。

現在,我正在做一些特別丑陋的事情,以根據任務名稱收集我需要的東西:

def v2_runner_on_ok(self, result):

    if result._task.action == 'archive':
        if result._task.name == 'Create archive foo':
            self.body['path'] = result._result['path']

    if result._task.action == 'ec2':
        if result._task.name == 'Start instance bar':
            self.body['ec2_id'] = result._result['id']

   # do it for every task which generates "interesting" info

顯然,如果任務名稱更改,此操作將無法縮放並中斷。

為了保持通用性,我一直在考慮就事實名稱達成一致,例如add_to_body ,只要存在,它將被添加到body字典中。 我喜歡這種方法,因為在播放過程中注冊幾個變量並在播放結束時使用它們來組合一個事實特別容易。 例:

---

- name: Demo play
  hosts: localhost
  gather_facts: False

  tasks:

    - name: Create temporary file 1
      tempfile:
        path: '/tmp'
      register: reg_tmp_1

    - name: Create temporary file 2
      tempfile:
        path: '/tmp'
      register: reg_tmp_2

    - name: Set add_to_body fact
      set_fact:
        add_to_body: "{{ { 'reg_tmp_1': reg_tmp_1.path,
                           'reg_tmp_2': reg_tmp_2.path } }}"

    - debug: var=add_to_body

但是,我無法找到一種方法來通過set_fact操作訪問事實的值,既set_fact查看result對象,也set_fact嘗試訪問當前主機的hostvars來實現(這顯然在回調插件中不可能的 )。

您建議如何解決此限制?

嗯,你在這里混一些東西。
如果要在每個任務之后在v2_runner_on_ok調用API,則應在任務上下文中處理add_to_body
但是在您的示例中,您在完成多個任務之后設置了add_to_body這樣,您最好編寫動作插件(例如send_to_my_service )並調用它,而不是使用必需的參數調用set_fact

這是在任務上下文中如何使用add_to_body的示例:

---
- hosts: localhost
  gather_facts: no

  tasks:
    - command: echo hello world
      vars:
        add_to_body:
          - path
    - file:
        dest: /tmp/zzz
        state: touch
      vars:
        add_to_body:
          - dest

打回來:

def v2_runner_on_ok(self, result):
    if 'add_to_body' in result._task.vars:
        res = dict()
        for i in result._task.vars['add_to_body']:
            if i in result._result:
                res[i] = result._result[i]
            else:
                display.warning('add_to_body: asked to add "{}", but property not found'.format(i))
        display.v(res)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM