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

Allow map filter to retrieve multiple items #554

Closed
Yannik opened this issue Feb 29, 2016 · 4 comments
Closed

Allow map filter to retrieve multiple items #554

Yannik opened this issue Feb 29, 2016 · 4 comments

Comments

@Yannik
Copy link

Yannik commented Feb 29, 2016

At the moment, the map function can only be used like this:

[{'path':'/var/file1', 'mtime': '123', 'mode': '600',...},{'path':'/var/file2', 'mtime': '123', 'mode': 644, ...}]|map(attribute='path')

with the return of

['/var/file1', '/var/file2']

(Docs: http://jinja.pocoo.org/docs/dev/templates/#map)

I want to propose allowing this:

[{'path':'/var/file1', 'mtime': '123', 'mode': '600',...},{'path':'/var/file2', 'mtime': '123', 'mode': 644, ...}]|map(attribute=['path', 'mtime'])

or

[{'path':'/var/file1', 'mtime': '123', 'mode': '600',...},{'path':'/var/file2', 'mtime': '123', 'mode': 644, ...}]|map(attributes=['path', 'mtime'])

which should return

[{'path':'/var/file1', 'mtime': '123'},{'path':'/var/file2', 'mtime': '123'}]

You can already see what this is useful for: manipulating a list of dicts so that these dicts only retain a limited set of attributes.

@ssenaria
Copy link

Would LOVE this feature.

@davidism
Copy link
Member

I'm not clear why this is needed in templates. Just iterating over the dictionaries and using the attributes you need will accomplish the same thing. If you need different data, it's probably a better idea to do that manipulation in Python before rendering. I could maybe see a use for it returning tuples.

@Nee6ione
Copy link

If anyone still needs this you can use the following code (put in 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

Use via:

ansible_mounts | mapattributes(['mount', 'size_total', 'size_available',])

@jdelvecchio

This comment has been minimized.

@pallets pallets locked as resolved and limited conversation to collaborators Oct 29, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants