Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fetchlistfromdict filter #15157

Closed
hryamzik opened this issue Mar 25, 2016 · 3 comments
Closed

fetchlistfromdict filter #15157

hryamzik opened this issue Mar 25, 2016 · 3 comments
Labels
feature This issue/PR relates to a feature request.

Comments

@hryamzik
Copy link
Contributor

ISSUE TYPE

  • Feature Idea
SUMMARY

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.

@amenonsen
Copy link
Contributor

{{ 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 }}

?

@hryamzik
Copy link
Contributor Author

@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!

@corny
Copy link
Contributor

corny commented Oct 1, 2016

This example should be included in the documentation. I search quite long before I found this issue.

@ansibot ansibot added feature This issue/PR relates to a feature request. and removed feature_idea labels Mar 2, 2018
@ansible ansible locked and limited conversation to collaborators Apr 25, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
feature This issue/PR relates to a feature request.
Projects
None yet
Development

No branches or pull requests

5 participants