AnsiblePilot โ€” Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,400 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of 8 Ansible books published by Apress and Leanpub 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 2024-01-01 ยท Category: troubleshooting

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

๐ŸŽฏ Filtering Data in Ansible: selectattr and map(attribute)

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 based on a condition. โ€ข map(attribute) โ†’ Extracts a specific field from the filtered result.

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('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 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 search_name: alice, the output will be:
TASK [Get folder for a specific user] *********************************************
ok: [localhost] => {
    "msg": [
        "/home/alice"
    ]
}

When search_name: bob, the output will be:

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

| Method | Output | |------------|------------| | | 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!

Related Articles

โ€ข Jinja2 templating in Ansible

Category: troubleshooting

Browse all Ansible tutorials ยท AnsiblePilot Home