AnsiblePilot โ€” Ansible Automation Platform and Enterprise Ansible

AnsiblePilot covers Red Hat Ansible Automation Platform (AAP) and enterprise Ansible: install and upgrade paths, Event-Driven Ansible, security and day-2 operations, plus Luca Berton's books, videos and training.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of 9 technical books published by Apress and Leanpub, 4 of them on Ansible, including "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example", and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

Ansible select & selectattr Filters: Filter Lists by Condition (Guide)

By Luca Berton ยท Published 2025-01-29 ยท Category: troubleshooting

How to filter lists in Ansible with select, selectattr, and map filters. Filter by attribute, test conditions, chain filters.

Ansible selectattr: Filter Lists by Attribute with Examples

Ansible selectattr is a Jinja2 filter that filters a list of dictionaries by attribute, keeping only items where an attribute matches a test condition (such as equalto, defined, match, or search).

When working with lists of dictionaries in Ansible, filtering and extracting specific values is a common requirement. Jinja2 provides two powerful filters to accomplish this:

  • selectattr โ†’ Filters the list by an attribute condition.
  • map(attribute) โ†’ Extracts a specific field from each filtered item.
In this article, you'll learn:
  • โœ… How to filter lists of dictionaries in Ansible using selectattr
  • โœ… How to extract specific values using map(attribute)
  • โœ… How to handle missing values safely using default()
---

See also: Ansible map vs selectattr vs json_query: Filter Data the Right Way

๐Ÿ“Œ Understanding selectattr and map(attribute)

Before jumping into Ansible playbooks, let's break down these Jinja2 filters.

selectattr(attribute, test, value) takes the name of a dictionary key, an optional Jinja2 test (equalto, defined, match, search, in, and so on) and an optional value to compare against. With only the attribute name, for example selectattr('enabled'), it keeps items where that attribute is truthy. Use rejectattr for the opposite selection.

โœ… selectattr('name', 'equalto', search_name)

  • Filters a list of dictionaries to select only the ones where name == search_name.

โœ… map(attribute='folder')

  • Extracts the folder field from the filtered result.

โœ… Example Syntax

{{ variable | selectattr('name', 'equalto', search_name) | map(attribute='folder') | list }}
  • selectattr filters the list where name equals search_name.
  • map(attribute='folder') extracts only the folder values.
  • list ensures the result is returned as a list.
---

๐Ÿ”ฅ Example Use Case

Scenario

You have a list of users and their home directories (folder). You want to search for a specific user using selectattr and get their folder path.

Example Data

variable:
  - name: alice
    folder: /home/alice
  - name: bob
    folder: /home/bob
  - name: charlie
    folder: /home/charlie

Using selectattr and map(attribute) in Ansible

- name: Search for a name and get its folder
  hosts: localhost
  gather_facts: no
  vars:
    variable:
      - name: alice
        folder: /home/alice
      - name: bob
        folder: /home/bob
      - name: charlie
        folder: /home/charlie
    search_name: alice
  tasks:
    - name: Get folder for a specific user
      debug:
        msg: "{{ variable | selectattr('name', 'equalto', search_name) | map(attribute='folder') | list }}"

---

See also: Ansible 2.16.0: Major Enhancements and Updates

๐ŸŽฏ Expected Output

When you use selectattr in Ansible, it returns a filtered list containing only the dictionaries that match the condition. Piping that result through map(attribute='folder') reduces it to a plain YAML list of the matched folder values, as shown below. When the Ansible playbook executes the selectattr filter successfully, it extracts the matching folder path and displays it in the task result. Here's what you'll see for each scenario:

When search_name: alice:

TASK [Get folder for a specific user] *********************************************
ok: [localhost] => {
    "msg": [
        "/home/alice"
    ]
}

When search_name: bob:

TASK [Get folder for a specific user] *********************************************
ok: [localhost] => {
    "msg": [
        "/home/bob"
    ]
}

---

๐Ÿ”น Getting a Single Value Instead of a List

By default, the output is a list with one value. If you need only the string value, add .0:
- name: Get a single folder for a user
  debug:
    msg: "{{ (variable | selectattr('name', 'equalto', search_name) | map(attribute='folder') | list).0 }}"

๐Ÿ“Œ Expected Output

TASK [Get a single folder for a user] *********************************************
ok: [localhost] => {
    "msg": "/home/alice"
}

---

See also: Ansible selectattr Filter: Filter Lists by Attributes (Guide)

๐Ÿšจ Handling Missing Values Gracefully

If the search_name does not exist in the list, you may encounter an error. To prevent this, use default():
- name: Get folder safely
  debug:
    msg: "{{ (variable | selectattr('name', 'equalto', search_name) | map(attribute='folder') | list | default(['/not-found'])).0 }}"

๐Ÿ“Œ Expected Output When search_name is Missing

TASK [Get folder safely] *********************************************
ok: [localhost] => {
    "msg": "/not-found"
}

---

โœ… Summary Table

MethodOutput
list["/home/alice"]
.0"/home/alice"
default(['/not-found'])"/not-found" if no match
---

๐Ÿš€ Why Use This Approach?

โœ” Filters data dynamically โœ” Extracts only necessary values โœ” Handles missing values safely โœ” Works efficiently with lists of dictionaries

These Jinja2 filters are invaluable when working with structured data in Ansible playbooks!

Category: troubleshooting

Browse all Ansible tutorials ยท AnsiblePilot Home