Filter a list of dict

Hello!

I have a list of dicts with network definitions for an opnsense:

networks_test:
  - descr: UpLink
    iface: wan
    vlan_id: '7'

  - descr: MgmtNet
    iface: lan
    vlan_id: '40'
  - descr: HomeNet
    iface: opt1

In order to configure my vlans, I need a list of the keys ‘descr’ but only, if there is a ‘vlan_id’ defined in the same dictionary.

I can create the list of ‘descr’:

- name: get list of VLANs
  ansible.builtin.set_fact:
    vlan_config: {{ networks_test | map(attribute='descr') }}

But how can I filter for the existence of the ‘vlan_id’ key?
In my case, the result should be:

"vlan_config": ["Uplink", "MgmtNet"]}

Thanks a lot!

Just written, the solution came to my mind:

    - name: get list of configured VLANs
      ansible.builtin.set_fact:
        vlan_config: "{{ networks_test | selectattr('vlan_id', 'defined') | map(attribute='descr') }}"

Sorry for the question!

2 Likes