Jinja2 map( ) Filter

Reference: jinja

Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it.

The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames:

Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence:


Reference: OzNetNerd.com

The code below passes the names  dictionary to the map  filter on four separate occasions to demonstrate the ways in which it can be used:

Output #1

In this run we see that the map(attribute='first')  filter prints the “first” values of the Key Value pairs:

Output #2

Similar to the previous run, we see that the map(attribute='last')  filter prints the “last” values of the Key Value pairs:

Output #3

This example differs from the previous two in that we’re passing the upper  Jinja filter to map  as opposed to an attribute:

Output #4

This example demonstrates how we can chain two map  filters. Note that one is being passed an attribute while the other is being passed the upper  filter:

Cisco Example

The following Playbook uses map()  to extract interface information from Cisco devices:

Running this Playbook results in the following output:


These Playbooks are available in the map() section of my Github repo.

Knowledge Base

See the Ansible section of my Knowledge Base for more information.

As always, if you have any questions or have a topic that you would like me to discuss, please feel free to post a comment at the bottom of this blog entry, e-mail at will@oznetnerd.com, or drop me a message on Twitter (@OzNetNerd).

Note: This website is my personal blog. The opinions expressed in this blog are my own and not those of my employer.