🌐
Ansible
docs.ansible.com › projects › ansible › latest › playbook_guide › complex_data_manipulation.html
Manipulating data — Ansible Community Documentation
- hosts: localhost tasks: - name: ...ttr("1.ansible_host", "defined")|map(attribute="0")|list }}' This example uses Python argument list unpacking to create a custom list of fileglobs based on a variable....
Discussions

python - Ansible - how to use selectattr with yaml of different keys - Stack Overflow
Is selectattr filter expecting all the dicts in the list to have the same keys?Because it does not make any sense not to be able to filter a list of custom dicts with Jinja2. For example if i had a more complicated yaml (not that flat) am i limited to search and filter within Ansible? More on stackoverflow.com
🌐 stackoverflow.com
jinja2 - Ansible variable selectattr then map then equality - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
jinja2 - Ansible: filter a list by its attributes - Stack Overflow
Ansible also has the tests match and search, which take regular expressions: match will require a complete match in the string, while search will require a match inside of the string. network.addresses.private_man | selectattr("type", "match", "^fixed$") More on stackoverflow.com
🌐 stackoverflow.com
jinja2 - Passing a var into a selectattr statment in Ansible - Stack Overflow
I am looping through a dict "aws_ec2_volums_setting" and i am trying to pass the loop variable item.id to a "selectattr" statement to get a list that meets the criteria. - name: Set Filters se... More on stackoverflow.com
🌐 stackoverflow.com
🌐
AnsiblePilot
ansiblepilot.com › articles › filtering-data-in-ansible-selectattr-and-map
Filtering Data in Ansible: selectattr and map(attribute)
January 29, 2025 - msg: "{{ (variable | selectattr('name', 'equalto', search_name) | map(attribute='folder') | list).0 }}"
🌐
Middleware Inventory
middlewareinventory.com › blog › ansible-selectattr-example
Ansible selectattr Example - Filter dictionary and select matching item
February 24, 2024 - --- - name: selectattr example - Vaccination Report hosts: localhost tasks: - name: debug vars: - userdata: [ { "name": "Shanmugam", "gender": "male", "mobile": "9875643210", "dose1completed" : "yes", "dose2completed" : "yes", "age": "25", "city": ...
🌐
How to Use Linux
howtouselinux.com › home › selectattr in ansible
selectattr in Ansible - howtouselinux
October 9, 2025 - - hosts: localhost vars: users: - name: john age: 25 - name: jane age: 30 - name: bob age: 20 tasks: - name: Get users over 25 debug: var: users | selectattr('age', '>=', 25) | map(attribute='name') | list · This is an Ansible playbook that targets the localhost host, which is the machine where the playbook is being executed.
🌐
Packetswitch
packetswitch.co.uk › ansible-selectattr-filter
How to use Ansible 'selectattr' Filter?
September 21, 2024 - It is required because the selectattr filter returns an iterable object, which needs to be converted to a list for further use or display in Ansible. When combined, the expression creates a new list called red_fruits, containing only those dictionaries from the fruits list with a 'color' attribute equal to 'red'. PLAY [Simple selectattr Filter Example] ********************************** TASK [Create a list of red fruits] ******************************************* ok: [127.0.0.1] TASK [Display red fruits] ********************************************** ok: [127.0.0.1] => { "red_fruits": [ { "color": "red", "name": "apple" }, { "color": "red", "name": "cherry" } ] } PLAY RECAP ************************************** 127.0.0.1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Top answer
1 of 2
8

Is selectattr filter expecting all the dicts in the list to have the same keys?

More precisely, it is expecting all dicts in the list to have the attribute you are selecting on. If not all dict in the list have it, you will have to first filter out the items where it is not defined. This can be done with selectattr as well. (thanks @Randy for making this clearer since my initial answer).

In your situation, the json_query filter (which implements jmespath) can also do the job in sometimes a more compact manner. But it is not a core filter and requires to have the community.general collection installed.

Here are a few examples taken from your above requirements solved with both core filters and json_query solutions.

The playbook:

---
- name: "Filter data with core filters or json query"
  hosts: "localhost"
  gather_facts: false

  vars:
    # Your initial data on a single line for legibility
    test_var: [{"vm":"vm1","ip":"10.10.10.1"},{"vm":"vm2","ip":"10.10.10.2"},{"test_vm":"something","process_1":"X","process_2":"Y","process_3":"Z"},{"another_vm":"something_other"}]

  tasks:
    - name: Get objects having vm==vm1
      vars:
        msg: |-
          With core filters: {{ test_var | selectattr('vm', 'defined') | selectattr('vm', '==', 'vm1') | list }}
          With json_query: {{ test_var | json_query("[?vm=='vm1']") | list }}
      debug:
        msg: "{{ msg.split('\n') }}"

    - name: Get all objects having vm attribute
      vars:
        msg: |-
          With core filters: {{ test_var | selectattr('vm', 'defined') | list }}
          With json_query: {{ test_var | json_query("[?vm]") | list }}
      debug:
        msg: "{{ msg.split('\n') }}"

    - name: Get all objects having process_2 attribute
      vars:
        msg: |-
          With core filters: {{ test_var | selectattr('process_2', 'defined') | list }}
          With json_query: {{ test_var | json_query("[?process_2]") | list }}
      debug:
        msg: "{{ msg.split('\n') }}"

    - name: Get only a list of process_2 attributes
      vars:
        msg: |-
          With core filters: {{ test_var | selectattr('process_2', 'defined') | map(attribute='process_2') | list }}
          With json_query: {{ test_var | json_query("[].process_2") | list }}
      debug:
        msg: "{{ msg.split('\n') }}"

which gives:

PLAY [Filter data with core filters or json query] *********************************************************************

TASK [Get objects having vm==vm1] *********************************************************************
ok: [localhost] => {
    "msg": [
        "With core filters: [{'vm': 'vm1', 'ip': '10.10.10.1'}]",
        "With json_query: [{'vm': 'vm1', 'ip': '10.10.10.1'}]"
    ]
}

TASK [Get all objects having vm attribute] *********************************************************************
ok: [localhost] => {
    "msg": [
        "With core filters: [{'vm': 'vm1', 'ip': '10.10.10.1'}, {'vm': 'vm2', 'ip': '10.10.10.2'}]",
        "With json_query: [{'vm': 'vm1', 'ip': '10.10.10.1'}, {'vm': 'vm2', 'ip': '10.10.10.2'}]"
    ]
}

TASK [Get all objects having process_2 attribute] *********************************************************************
ok: [localhost] => {
    "msg": [
        "With core filters: [{'test_vm': 'something', 'process_1': 'X', 'process_2': 'Y', 'process_3': 'Z'}]",
        "With json_query: [{'test_vm': 'something', 'process_1': 'X', 'process_2': 'Y', 'process_3': 'Z'}]"
    ]
}

TASK [Get only a list of process_2 attributes] *********************************************************************
ok: [localhost] => {
    "msg": [
        "With core filters: ['Y']",
        "With json_query: ['Y']"
    ]
}

PLAY RECAP *********************************************************************
localhost                  : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
2 of 2
8

To complement this edit of Zeitounator's answer:

More precisely, it is expecting all dicts in the list to have the attribute you are selecting on.

It is not 100% true for all filter functions, to select objects by an attribute not defined by all elements:

{{ test_var | selectattr('vm','defined') |selectattr('vm','equalto','vm1') | list }} 
🌐
Tailored Cloud
tailored.cloud › home › advanced list operations in ansible
Advanced list operations in Ansible. selectattr, sum, map and others.
March 16, 2018 - Let’s first have a look and then ... "{{ interfaces | selectattr('name', 'match', 'eth[2-9]') | sum(attribute='ips', start=[]) | selectattr('owner', 'equalto', 'TEST') | map(attribute='ip') | list | first | default('NOT_FOUND') }}" - debug: msg: ...
Find elsewhere
🌐
Oznetnerd
oznetnerd.com › 2017 › 04 › 18 › jinja2-selectattr-filter
Jinja2 selectattr() Filter - OzNetNerd.com
April 17, 2017 - - debug: msg={{ network.addresses.private_man | selectattr("type", "equalto", "floating") | map(attribute='addr') | list }} - debug: msg={{ network.addresses.private_man | selectattr("type", "match", "^floating$") | map(attribute='addr') | list ...
🌐
0xf8
0xf8.org › 2021 › 03 › filtering-with-ansibles-selectattr-rejectattr-when-the-tested-attribute-can-be-absent
Filtering with Ansible’s selectattr()/rejectattr() when the tested attribute can be absent – 0xf8.org
March 19, 2021 - # default() makes no sense since it is applied to the generator returned by selectattr(): {{ fruit | selectattr('origin', 'equalto', 'exotic') | default('yes') }} # default() makes no sense since it would be applied to the string 'origin': {{ fruit | selectattr('origin' | default('exotic'), ...
Top answer
1 of 1
1

Create a dictionary of usernames and their visibility. For example, given the below data for testing

  result:
    json:
      - {username: mike, visibility: private}
      - {username: alice, visibility: public}
      - {username: bob, visibility: top secret}

Declare the dictionary

  username_visibility: "{{ result.json|
                           items2dict(key_name='username',
                                      value_name='visibility') }}"

gives

  username_visibility:
    alice: public
    bob: top secret
    mike: private

Now, the testing is trivial

  username_visibility.mike == 'private'

Example of a complete playbook for testing

shell> cat pb.yml
- hosts: localhost

  vars:

    result:
      json:
        - {username: mike, visibility: private}
        - {username: alice, visibility: public}
        - {username: bob, visibility: top secret}

    username_visibility: "{{ result.json|
                             items2dict(key_name='username',
                                        value_name='visibility') }}"

  tasks:

    - debug:
        var: username_visibility

    - assert:
        that: username_visibility.mike == 'private'

gives

shell> ansible-playbook pb.yml

PLAY [localhost] *****************************************************************************

TASK [debug] *********************************************************************************
ok: [localhost] => 
  username_visibility:
    alice: public
    bob: top secret
    mike: private

TASK [assert] ********************************************************************************
ok: [localhost] => changed=false 
  msg: All assertions passed

PLAY RECAP ***********************************************************************************
localhost: ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
🌐
Educative
educative.io › answers › how-to-filter-a-list-by-its-attributes-in-ansible
How to filter a list by its attributes in Ansible
--- - name: Filter a list in Ansible ... var: filtered_people vars: filtered_people: "{{ people | selectattr('age', '>', 30) | selectattr('gender', 'eq', 'male') | list }}"...
🌐
Ansiblebyexample
ansiblebyexample.com › home › articles › playbooks › filter a list by its attributes - ansible selectattr filter
Filter A List By Its Attributes - Ansible selectattr filter
June 24, 2024 - ansible-pilot $ ansible-playbook -i virtualmachines/demo/inventory variables/selectattr.yml PLAY [selectattr Playbook] **************************************************************************** TASK [Gathering Facts] **************************************************************************** ok: [demo.example.com] TASK [all features] ******************************************************************************* ok: [demo.example.com] => { "ansible_facts.eth1.features": { "esp_hw_offload": "off [fixed]", "esp_tx_csum_hw_offload": "off [fixed]", "fcoe_mtu": "off [fixed]", "generic_receive_of
Top answer
1 of 1
4

You are using the select filter wrongly with rather weird argument (I suspect a copy/paste error but I'm not sure). select will apply a test to each object in the list. I don't know any search test that can be applied to a hashmap (The closest I can think of is the python search method of an re -i.e. regexp- object which would not be appropriate anyway)

In your case, you are looking for a specific value of an attribute of your hashmap. This can be done with the selectattr filter which will apply a test to a given attribute of the objects in the list and return only the ones passing the test.

There is a different approach to your problem which is more compact IMO using the json_query filter

Below is an example playbook using both approaches leading to the same result.

---
- name: Sum size of FS
  hosts: localhost
  gather_facts: false

  vars:
    FS:
      - nom_FS: /appm/oracle/product
        nom_LV: lv_product
        size_FS: 5
        owner_FS: oracle
        group_FS: dba
        vg_name: vgapplis

      - nom_FS: /appm/oracle/product/12.1.0.2
        nom_LV: lv_12102
        size_FS: 15
        owner_FS: oracle
        group_FS: dba
        vg_name: vgapplis

      - nom_FS: /apps/oracle/logs
        nom_LV: lvlogs
        size_FS: 5
        owner_FS: oracle
        group_FS: dba
        vg_name: vglogs

  tasks:

    - name: Calculate with selectattr, map and sum
      debug:
        msg: "{{ FS | selectattr('vg_name', '==', 'vgapplis') | map(attribute='size_FS') | list | sum }}"

    - name: Calculate with json_query
      vars:
        sum_query: "[?vg_name=='vgapplis'].size_FS | sum(@)"
      debug:
        msg: "{{ FS | json_query(sum_query) }}"

And the result

PLAY [Sum size of FS] ****************************************************************

TASK [Calculate with selectattr, map and sum] ****************************************
ok: [localhost] => {
    "msg": "20"
}

TASK [Calculate with json_query] *****************************************************
ok: [localhost] => {
    "msg": "20"
}

PLAY RECAP ***************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
🌐
OneUptime
oneuptime.com › home › blog › how to use the selectattr and rejectattr filters in ansible
How to Use the selectattr and rejectattr Filters in Ansible
February 21, 2026 - # conditional_deploy.yml - Conditional deployment based on filtered data - name: Deploy only if there are active servers ansible.builtin.template: src: config.j2 dest: /etc/myapp/config.yml when: (servers | selectattr('enabled') | list | length) > 0 - name: Send alert if too many servers in maintenance ansible.builtin.uri: url: "https://alerts.example.com/webhook" method: POST body: text: "{{ servers | selectattr('status', 'eq', 'maintenance') | list | length }} servers in maintenance" body_format: json when: (servers | selectattr('status', 'eq', 'maintenance') | list | length) > 2
🌐
Network to Code
networktocode.com › home › manipulating data with jinja map and selectattr
Manipulating Data with Jinja Map and Selectattr - Network to Code
October 15, 2024 - Manipulating data with the Jinja filters, Map, Selectattr, and Select provides quick and efficient ways to create new data structures. This can simplify creating lookup dictionaries and avoids complex loops or Jinja templating options. In many instances in ansible, I’ll use an ordered list ...
🌐
Red Hat
redhat.com › en › blog › ansible-jinja-lists-dictionaries
How to work with a list of dictionaries in Ansible
[ Write your first Ansible playbook in this hands-on interactive lab. ] Now that the tasks are defined, put it altogether in a single playbook: --- - name: 'Jinja selectattr() and map() example with list of dictionaries' hosts: localhost gather_facts: false vars: # This is a list of dictionaries bands: - name: The Beatles members: - Lennon - McCartney - Harrison - Starr formed: 1960 decade: 60s - name: The Eagles members: - Frey - Henley - Leadon - Meisner formed: 1971 decade: 70s - name: Run DMC members: - Simmons - McDaniels - Mizell formed: 1983 decade: 80s - name: Red Hot Chili Peppers mem