🌐
Middleware Inventory
middlewareinventory.com › blog › ansible-selectattr-example
Ansible selectattr Example - Filter dictionary and select matching item
February 24, 2024 - Ansible selectattr filter is basically an inherited version of Jinja selectattr filter. As Ansible Quotes in their documentation besides the built-in Ansible filters, all JINJA2 filters can be used in Ansible playbooks.
Discussions

python - Ansible - how to use selectattr with yaml of different keys - Stack Overflow
im pulling my hairs trying to do a simple thing (i thought it should be easy) with parsing a yaml and filtering for some key in Ansible. My yaml file looks like this: --- - vm: "vm1" ip: 10.10... 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
selectattr with ansible - Ansible Project - Ansible
Hi, I have a list like below, and I need to select the sequence which has “name” attribute equal to “lo0”. I use this selectattr statement {% set lo0 = interfaces|selectattr(“name”, “equalto”, lo0) | first%} But while … More on forum.ansible.com
🌐 forum.ansible.com
0
July 5, 2015
selectattr question
you can use an in operator to check if the value of column1 is in a list. - name: trimadata set_fact: trimeddata: "{{ data|selectattr('column1', 'in', select_list) }}" vars: select_list: - type1 - type2 More on reddit.com
🌐 r/ansible
4
2
March 2, 2022
🌐
How to Use Linux
howtouselinux.com › home › selectattr in ansible
selectattr in Ansible - howtouselinux
October 9, 2025 - selectattr in Ansible selectattr is a filter plugin in Ansible that allows you to select a subset of elements from a list of dictionaries based on the value of a particular attribute. Its syntax is as follows: | selectattr(' ', ' ', ' ') Key Description list_of_dictionaries A list of dictionaries ...
🌐
Ansible
docs.ansible.com › projects › ansible › latest › playbook_guide › playbooks_tests.html
Tests — Ansible Community Documentation
vars: lacp_groups: - master: lacp0 network: 10.65.100.0/24 gateway: 10.65.100.1 dns4: - 10.65.100.10 - 10.65.100.11 interfaces: - em1 - em2 - master: lacp1 network: 10.65.120.0/24 gateway: 10.65.120.1 dns4: - 10.65.100.10 - 10.65.100.11 interfaces: - em3 - em4 tasks: - debug: msg: "{{ (lacp_groups|selectattr('interfaces', 'contains', 'em1')|first).master }}"
🌐
Tailored Cloud
tailored.cloud › home › advanced list operations in ansible
Advanced list operations in Ansible. selectattr, sum, map and others.
March 16, 2018 - The problem can be solved with the following ansible code. Let’s first have a look and then I will explain it step by step: # file playbook.yml - hosts: all tasks: - set_fact: test_ip: "{{ 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: "The TEST IP is {{ test_ip }}" In line 5, we start with our list of interface configurations, created from both “interfaces_eth1” and “interfaces_eth2”, which are one-element lists.
🌐
Packetswitch
packetswitch.co.uk › ansible-selectattr-filter
How to use Ansible 'selectattr' Filter?
September 21, 2024 - Loops in Ansible are like shortcuts for doing the same task many times. Instead of repeating the same steps over and over again, we use a loop to do the task as many times ... Let's say we only want to create a list containing only the names of the red fruits. let's use the map() filter along with selectattr() to create a new list containing the names of red fruits from the given fruits list. In this playbook, the map() filter is added after the selectattr() filter.
🌐
AnsiblePilot
ansiblepilot.com › articles › filtering-data-in-ansible-selectattr-and-map
Filtering Data in Ansible: selectattr and map(attribute)
January 29, 2025 - selectattr → Filters the list based on a condition. map(attribute) → Extracts a specific field from the filtered result. ... Before jumping into Ansible playbooks, let's break down these Jinja2 filters.
🌐
Educative
educative.io › answers › how-to-filter-a-list-by-its-attributes-in-ansible
How to filter a list by its attributes in Ansible
The result of the previous filter is then further filtered using selectattr('gender', 'eq', 'male'), which selects only items with the gender attribute set to male. Finally, the filtered result is converted into a list and assigned to the filtered_people variable. When you run this Ansible playbook, it will print the filtered_people variable containing the filtered list of people who are older than 30 and are male.
Find elsewhere
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   
🌐
Red Hat
redhat.com › en › blog › ansible-jinja-lists-dictionaries
How to work with a list of dictionaries in Ansible
November 24, 2025 - selectattr() filters a sequence of objects by applying a test to the specified attribute of each object and only selecting the objects when the test succeeds. map() applies a filter on a sequence of objects or looks up an attribute.
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 }} 
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
🌐
AnsiblePilot
ansiblepilot.com › articles › filter-a-list-by-its-attributes-ansible-selectattr-filter
Filter A List By Its Attributes - Ansible selectattr filter | Ansible Pilot
Filters a sequence of objects by applying a test to the specified attribute of each object, and only selecting the objects with the test succeeding. If no test is specified, the attribute's value will be evaluated as a boolean.
🌐
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 - {{ fruit | selectattr('or', 'origin', 'not', 'defined', 'origin', 'equalto', 'exotic') }} # selectattr/rejectattr do not support brackets either {{ fruit | selectattr('or'(('origin', 'not', 'defined'), ('origin', 'equalto', 'exotic'))) }}
🌐
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 - When you have a list of dictionaries ... list based on the value of a specific attribute. The selectattr filter keeps items where an attribute passes a test, and rejectattr removes items where an attribute passes a test...
🌐
Linux Hint
linuxhint.com › ansible-selectattr-rejectattr
Ansible Selectattr/Rejectattr – Linux Hint
[root@master ansible]# ansible-playbook ansible_filter.yml · Here is the required showcase by utilizing the selectattr attribute in the playbook. As you have seen, we have gotten a very long output because we have used the gathering fact option as a true in the playbook.
🌐
Ansible
forum.ansible.com › archives › ansible project
selectattr with ansible - Ansible Project - Ansible
July 5, 2015 - Hi, I have a list like below, and I need to select the sequence which has “name” attribute equal to “lo0”. I use this selectattr statement {% set lo0 = interfaces|selectattr(“name”, “equalto”, lo0) | first%} But while …
🌐
Reddit
reddit.com › r/ansible › selectattr question
r/ansible on Reddit: selectattr question
March 2, 2022 -

I'm trying to trim down a load of data (spreadsheet import) and have been using selectattr to good effect - like this...

- name: trimdata

set_fact:

trimeddata: "{{ data|selectattr('column1', 'search', 'type1') }}"

my question is how do I perform an OR - so I trim down the data if its type1 OR type2 - I have been feeding this to another filter but that doesn't work as all the type2s have gone at that point.. I can create 2 trimmed variables (type1 and type2) and then add them together I guess but it doesn't feel very elegant.. (not that my code ever is!!!) - I googled for this and whilst I could get many examples of people doing stuff I was unable to get any proper documentation on any of this... the search operator I am using for example I just grabbed from somebody elses code but I don't *really* know what it does... and what other operators can go there that might help? dunno jinja documentation seems non-existent? I assume I am missing something :-)

Any ideas or pointers? (aside from a new career path)