Bootstrap

Ansible - plugin - filter

filter:

{{ value | function}}

输出的就是function(value)

 

将 value 当参数,执行 | 后边的function,可以执行ansible带的,也可以自己定义。

在自定义中,先创建类,类名统一为 FilterModule, 类只需要建一个方法,filter,用来返回执行的函数。

具体执行的function可以写在类外边。

 

==============================================================

例:

vim plugins/filter/union_all.py

def union_all(a):
    result = dict()
    for item in a:
        result.update(item)
    return result

class FilterModule(object):
   '''Additional math utilities
   Called more_math_stuff because its in addition to the core filter plugin math_stuff
   '''
   def filters(self):
       return {
          'union_all': union_all
       }

在ansible 中使用

{{ value | union_all }}

输出的就是union_all(value)

vim test.yml

---
- hosts: all
  remote_user: root
  gather_facts: no
  vars:
    list1: [{'a':'a'}, {'b':'b'}, {'c':'c'}]
  tasks:
    - name: test01
      debug:
        msg: "{{ list1 | union_all }}"

 

运行结果

TASK [test01] *****************************************************************************
task path: /root/ansible-test/test.yml:14
ok: [XXXXX] => {
    "msg": {
        "a": "a",
        "b": "b",
        "c": "c"
    }
}

 

 

;