Home > OS >  How to build a list of subelements from list of dictionaries in Ansible
How to build a list of subelements from list of dictionaries in Ansible

Time:10-20

Please help me to build a list of subelements from a list of dictionaries using one line filter

vars:
  source_list:
      - { name: 'name1', addr: 'ip1' }
      - { name: 'name2', addr: 'ip2' }
      - { name: 'name3', addr: 'ip3' }
  dest_list: "{{ source_list | XXXXXX }}"

debug: var=dest_list output should look like this

[ 'ip1', 'ip2', 'ip3' ]

thanks in advance

CodePudding user response:

Just use map(attribute='addr'), this will extract the values of the specified attribute from a list of dicts.

The task:

- debug:
    msg: "{{ dest_list }}"
  vars:
    source_list:
        - { name: 'name1', addr: 'ip1' }
        - { name: 'name2', addr: 'ip2' }
        - { name: 'name3', addr: 'ip3' }
    dest_list: "{{ source_list | map(attribute='addr') }}"

Returns the following result:

TASK [debug] *****************
ok: [localhost] => {
    "msg": [
        "ip1",
        "ip2",
        "ip3"
    ]
}
  • Related