Let's say you have an array of dictionaries and you would like to build an array with some dictionary attributes. There're several methods to do this: selectattr, map and the new extract filter.
That works great until you decide to use hosts of some group as an initial array of dictionaries. So you have to get hostvars
for each host in a group with a filter. We can usually workaround this with some jinja iterations but that doesn't work for setting variables.
That said there's a solution:
def fetchlistfromdict(d, l):
result = []
for item in l:
result.append(d[item])
return result
class FilterModule(object):
def filters(self):
return {
'fetchlistfromdict': fetchlistfromdict,
}
And now:
{{ hostvars|fetchlistfromdict(groups['webservers']) |map(attribute='custom_facts.aliases.0.ip')|list}}
This case seem to be very specific and might be route53
module related.
So can we add this filter to ansible? Shall I make a PR? What about the naming? I've saved the original one but list_from_dict
looks better for me.
{{ hostvars|fetchlistfromdict(groups['webservers']) |map(attribute='custom_facts.aliases.0.ip')|list}}
What does this do differently from
{{ groups['webservers']|map('extract', hostvars, ['custom_facts','aliases','0','ip'])|list }}
?
@amenonsen good point, I've only tried to get this with map(attribute=
, looks like the new extract filter does the job, looking forward to play with it in a new release!
This example should be included in the documentation. I search quite long before I found this issue.
Most helpful comment
This example should be included in the documentation. I search quite long before I found this issue.