Creating new list from values in list of dicts

89 views
Skip to first unread message

Rob White

unread,
Sep 13, 2015, 9:19:48 PM9/13/15
to Ansible Project
Hi all,

I am using the ec2_vpc_subnet_facts module to get back a list of subnet dicts.  I want to get the id from each of these dicts and add it to a new list so i end up with just a list of subnet ids.  I thought this might be possible with existing jinja filters but i'm not sure where to start so any pointers would be appreciated.

Example:

'subnets': [{u'availability_zone': u'ap-southeast-2a', u'tags': {u'Type': u'public', u'Zone': u'a', u'Env': u'support', u'Name': u'support-public-a'}, u'default_for_az': u'false', u'state': u'available', u'vpc_id': u'vpc-11223344', u'cidr_block': u'10.66.128.0/25', u'available_ip_address_count': 113, u'id': u'subnet-11223344', u'map_public_ip_on_launch': u'false'}, {u'availability_zone': u'ap-southeast-2b', u'tags': {u'Type': u'public', u'Zone': u'b', u'Env': u'support', u'Name': u'support-public-b'}, u'default_for_az': u'false', u'state': u'available', u'vpc_id': u'vpc-11223344', u'cidr_block': u'10.66.129.0/25', u'available_ip_address_count': 118, u'id': u'subnet-55667788', u'map_public_ip_on_launch': u'false'}]


I want to get each subnet.id in to a list so i end up with...

my_list: [subnet-11223344, subnet-55667788]

Thanks,

Rob White

unread,
Sep 13, 2015, 9:55:34 PM9/13/15
to Ansible Project
So I wrote my own filter for this...

def idfromlistofdicts(l):
    result
= []
   
for item in l:
        result
.append(item['id'])


   
return result


class FilterModule(object):
   
def filters(self):
       
return {
           
'idfromlistofdicts': idfromlistofdicts,
       
}


Not sure if something like this already exists though.

Takeshi Yaegashi

unread,
Sep 14, 2015, 12:31:17 AM9/14/15
to Ansible Project
Hello,

Try the following playbook:

---
- hosts: all
  gather_facts: no
  vars:
    subnets: [ { id: subnet-11223344 }, { id: subnet-55667788 } ]
    my_list: |
      {%- set o = [] %}
      {%- for i in subnets %}
      {%-   if o.append(i.id) %}
      {%-   endif %}
      {%- endfor %}
      {{ o }}
  tasks:
    - debug:
        var: my_list


Sample session:

$ ansible-playbook -i localhost, playbook.yml

PLAY [all] ******************************************************************** 

TASK: [debug ] **************************************************************** 
ok: [localhost] => {
    "var": {
        "my_list": [
            "subnet-11223344", 
            "subnet-55667788"
        ]
    }
}

PLAY RECAP ******************************************************************** 
localhost                  : ok=1    changed=0    unreachable=0    failed=0   

Regards,
--  
YAEGASHI Takeshi <yaeg...@debian.org>
Reply all
Reply to author
Forward
0 new messages