Jinja Map: How to Extract Specific Values From a List of Dictionaries

Jinja Map: How to Extract Specific Values From a List of Dictionaries

Jinja Tip:
Use Jinja's map to extract specific values from a list of dictionaries. Perfect for pulling out IPs, interfaces, or other attributes within your Jinja templates or Ansible playbooks.

Example below:

# Input data
interfaces: 
  - { device: 'spine1', interface: 'GigabitEthernet0/0', ip: '10.1.1.1' }
  - { device: 'spine1', interface: 'GigabitEthernet0/1', ip: '10.1.2.1' }
  - { device: 'spine2', interface: 'GigabitEthernet0/0', ip: '10.2.1.1' }
  - { device: 'spine2', interface: 'GigabitEthernet0/1', ip: '10.2.2.1' }
  - { device: 'leaf1',  interface: 'GigabitEthernet0/0', ip: '10.1.1.2' }
  - { device: 'leaf1',  interface: 'GigabitEthernet0/1', ip: '10.2.1.2' }
  - { device: 'leaf2',  interface: 'GigabitEthernet0/0', ip: '10.1.2.2' }
  - { device: 'leaf2',  interface: 'GigabitEthernet0/1', ip: '10.2.2.2' }

# Jinja syntax
{{ interfaces | map(attribute='ip') | list | pprint }}

# Result 
[
  '10.1.1.1',
  '10.1.2.1',
  '10.2.1.1',
  '10.2.2.1',
  '10.1.1.2',
  '10.2.1.2',
  '10.1.2.2',
  '10.2.2.2'
]
Try it yourself

Subscribe to our newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox.
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!