Search code examples
ansiblejinja2

Filter a specific attribute of nested lists with Jinja


I have an input data as a list of lists. On this data, I want to apply a filter and collect the list of attributes from the element of lists.

Following is the example input JSON data which list of lists:

[
   [
      {
         "device_name":"/dev/sda1",
         "ebs":{
            "delete_on_termination":true,
            "snapshot_id":"snap-0456a553a80e6826a",
            "volume_size":30,
            "volume_type":"gp2",
            "encrypted":true
         }
      }
   ],
   [
      {
         "device_name":"/dev/sda1",
         "ebs":{
            "delete_on_termination":true,
            "snapshot_id":"snap-001c3143228559631",
            "volume_size":30,
            "volume_type":"gp2",
            "encrypted":true
         }
      }
   ],
   [
      {
         "device_name":"/dev/sda1",
         "ebs":{
            "delete_on_termination":true,
            "snapshot_id":"snap-040d15cdb5d8aaf33",
            "volume_size":30,
            "volume_type":"gp2",
            "encrypted":true
         }
      }
   ]
]

I want to extract the snapshot_id attribute from this above data for all list elements. How can I do that using Jinja2?


Solution

  • Use the map filter to extract the first element — .0 — of those nested lists, as well as the required attribute — .ebs.snapshot_id.

    With a simplified version of your data, given:

    {%- set data = [
       [ { "ebs": { "snapshot_id": "snap-0456a553a80e6826a" } } ],
       [ { "ebs": { "snapshot_id": "snap-001c3143228559631" } } ],
       [ { "ebs": { "snapshot_id": "snap-040d15cdb5d8aaf33" } } ],
    ] -%}
    
    {{ data | map(attribute="0.ebs.snapshot_id") | list }}
    

    This yields:

    ['snap-0456a553a80e6826a', 'snap-001c3143228559631', 'snap-040d15cdb5d8aaf33']