目前, map函数只能这样使用:
[{'path':'/var/file1', 'mtime': '123', 'mode': '600',...},{'path':'/var/file2', 'mtime': '123', 'mode': 644, ...}]|map(attribute='path')
随着回归
['/var/file1', '/var/file2']
(文档:http://jinja.pocoo.org/docs/dev/templates/#map)
我想提议允许这样做:
[{'path':'/var/file1', 'mtime': '123', 'mode': '600',...},{'path':'/var/file2', 'mtime': '123', 'mode': 644, ...}]|map(attribute=['path', 'mtime'])
或者
[{'path':'/var/file1', 'mtime': '123', 'mode': '600',...},{'path':'/var/file2', 'mtime': '123', 'mode': 644, ...}]|map(attributes=['path', 'mtime'])
哪个应该返回
[{'path':'/var/file1', 'mtime': '123'},{'path':'/var/file2', 'mtime': '123'}]
您已经可以看到这有什么用处:操作一个字典列表,以便这些字典只保留一组有限的属性。
会喜欢这个功能。
我不清楚为什么模板中需要这样做。 只需遍历字典并使用您需要的属性就可以完成同样的事情。 如果您需要不同的数据,最好在渲染之前在 Python 中进行操作。 我可能_可能_看到它返回元组的用途。
如果有人仍然需要这个,您可以使用以下代码(放入playbooks/filter_plugins/mapattributes.py
):
#!/usr/bin/env python
class FilterModule(object):
def filters(self):
return { 'mapattributes': self.mapattributes }
def mapattributes(self, list_of_dicts, list_of_keys):
l = []
for di in list_of_dicts:
newdi = { }
for key in list_of_keys:
newdi[key] = di[key]
l.append(newdi)
return l
使用方式:
ansible_mounts | mapattributes(['mount', 'size_total', 'size_available',])
为什么此问题已关闭且 Nee6ione 解决方案未正式实施? 如果在没有任何额外插件的情况下支持它,那将会简单得多
最有用的评论
如果有人仍然需要这个,您可以使用以下代码(放入
playbooks/filter_plugins/mapattributes.py
):使用方式: