filter
lookup
action
Using with filter as "|", default filters are usefully function to sort(min/max), format, select, tranform date out of Variable
After creating your own filter, by default, Ansible will look in the directory your playbook is located for a folder called ‘filter_plugins’ and load any filters it finds in that folder.
python 格式-1
#!/usr/bin/python
class FilterModule(object):
def filters(self):
return {
'a_filter': self.a_filter,
}
def a_filter(self, a_variable):
a_new_variable = a_variable + ' CRAZY NEW FILTER'
return a_new_variable
##################PLAYBOOK####################################
---
- hosts: localhost
tasks:
- name: Print a message
debug:
msg: "{{'test'|a_filter}}"
python 格式-2
#!/usr/bin/python
class FilterModule(object):
def filters(self):
return {
'a_filter': self.a_filter,
'another_filter': self.b_filter
}
def a_filter(self, a_variable):
a_new_variable = a_variable + ' CRAZY NEW FILTER'
return a_new_variable
def b_filter(self, a_variable, another_variable, yet_another_variable):
a_new_variable = a_variable + ' - ' + another_variable + ' - ' + yet_another_variable
return a_new_variable
##################PLAYBOOK####################################
---
- hosts: localhost
tasks:
- name: Print a message
debug:
msg: "{{'test'|another_filter('the','filters')}}"
add can be done by combine
If you interested in filter (which is in my opinion the cleanest way to delete an item in dict) then create filter_plugins/dicts.py in directory, which your playbook resides in, and fill it with:
'''Custom ansible filters for dicts'''
import copy
class FilterModule(object):
def filters(self):
return { 'del_by_list': self.del_by_list }
def del_by_list(self, dict_to_reduce, list_of_keys):
'''Deletes items of dict by list of keys provided'''
dict_to_return = copy.deepcopy(dict_to_reduce)
for item in list_of_keys:
if item in dict_to_return:
del dict_to_return[item]
return dict_to_return
Lookup plugins allow Ansible to access data from outside sources. This can include reading the filesystem in addition to contacting external datastores and services. Like all templating, these plugins are evaluated on the Ansible control machine, not on the target/remote.
vars:
file_contents: "{{lookup('file', 'path/to/file.txt')}}"
Together with customized Module, see more details in Module
Flatten only the first level of a list (akin to the items lookup):
{{ [3, [4, [2]] ] | flatten(levels=1) }}
# => [3, 4, [2]]
{{ [3, None, [4, [2]] ] | flatten(levels=1, skip_nulls=False) }}
# => [3, None, 4, [2]]