mirror of
https://github.com/ansible-collections/community.general.git
synced 2026-05-07 22:02:50 +00:00
Add an 'extract' filter
At its most basic, this is nothing more than an array or hash lookup,
but when used in conjunction with map, it is very useful. For example,
while constructing an "ssh-keyscan …" command to update known_hosts on
all hosts in a group, one can get a list of IP addresses with:
groups['x']|map('extract', hostvars, 'ec2_ip_address')|list
This returns hostvars[a].ec2_ip_address, hostvars[b].ec2_ip_address, and
so on. You can even specify an array of keys for a recursive lookup, and
mix string and integer keys depending on what you're looking up:
['localhost']|map('extract', hostvars, ['vars','group_names',0])|first
== hostvars['localhost']['vars']['group_names'][0]
== 'ungrouped'
Includes documentation and tests.
This commit is contained in:
@@ -339,6 +339,18 @@ def comment(text, style='plain', **kw):
|
||||
str_postfix,
|
||||
str_end)
|
||||
|
||||
def extract(item, container, morekeys=None):
|
||||
from jinja2.runtime import Undefined
|
||||
|
||||
value = container[item]
|
||||
|
||||
if value is not Undefined and morekeys is not None:
|
||||
if not isinstance(morekeys, list):
|
||||
morekeys = [morekeys]
|
||||
|
||||
value = reduce(lambda d, k: d[k], morekeys, value)
|
||||
|
||||
return value
|
||||
|
||||
class FilterModule(object):
|
||||
''' Ansible core jinja2 filters '''
|
||||
@@ -415,4 +427,7 @@ class FilterModule(object):
|
||||
|
||||
# comment-style decoration
|
||||
'comment': comment,
|
||||
|
||||
# array and dict lookups
|
||||
'extract': extract,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user