[英]How to use jinja2 filters to scrub dict values in ansible playbook
I have a playbook task that returns a list of dicts like this: 我有一个剧本任务,它返回像这样的字典列表:
mydict:
- { "ip": "192.168.0.1", "mac": "00324a:ac6789" }
- { "ip": "192.168.0.2", "mac": "00324a.ac6790" }
- { "ip": "192.168.0.3", "mac": "00:32:4a:ac:67:91" }
I would like to scrub the mac addresses so they all appear in the same format, something like: 我想清理Mac地址,使它们全部以相同的格式出现,例如:
- set_fact:
myarp: "{{ mydict|map(attribute='mac')|ipaddr('eui48') }}"
would return: 会回来:
myarp:
- { "ip": "192.168.0.1", "mac": "00-32-4A-AC-67-89" }
- { "ip": "192.168.0.2", "mac": "00-32-4A-AC-67-90" }
- { "ip": "192.168.0.3", "mac": "00-32-4A-AC-67-91" }
It won't work with map
because this filter either only returns one specific attribute OR applies another filter to each element of the list. 它不适用于
map
因为此过滤器要么只返回一个特定的属性,要么将另一个过滤器应用于列表的每个元素。 But you can not apply a filter to a specific attribute of each list element. 但是您不能将过滤器应用于每个列表元素的特定属性。 I don't think there is a way to do that with the built-in filters and if there is one, it gets too unreadable.
我认为没有办法使用内置过滤器来做到这一点,如果有的话,它就变得太难以理解了。
The best you can do here is to write a custom filter plugin : 您在这里可以做的最好的事情就是编写一个自定义过滤器插件 :
from ansible import errors
from jinja2.filters import environmentfilter
import re
class FilterModule(object):
def filters(self):
return {
'scrubmac': self.scrubmac
}
def scrubmac(*args):
data = args[1]
for item in data:
mac = re.sub('[^A-z0-9]', '', item['mac'])
item['mac'] = re.sub('(.{2})(?=.)', '\\1-', mac)
return data
That's for Ansible 2. Not sure, might need some small changes for Ansible 1. 这是针对Ansible 2的。不确定,可能需要对Ansible 1进行一些小的更改。
Then call it as 然后称它为
- set_fact:
myarp: "{{ mydict | scrubmac }}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.