BacklogZero®

Ansible in a Minute · Ansible Core ·

Use contains to test if a list has a value

Short answer

Use the contains test with selectattr to find a list item whose field includes a value.

Subscribe for updates

Get an email whenever we publish new guides and blog posts. Unsubscribe anytime.

By subscribing you agree we may email you about Ansible in a Minute and related Level Up Labs updates. We store your address in the same lead sheet as our contact form.

Request

print the LACP master whose interfaces list includes em1

Example

A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.

YAML
---
- name: Retrieve LACP Group Master
  hosts: all
  gather_facts: false
  vars:
    lacp_groups:
      - name: lacp0
        interfaces: [em1, em2]
        master: lacp0_master
      - name: lacp1
        interfaces: [em3, em4]
        master: lacp1_master
  tasks:
    - name: Find LACP group with em1
      ansible.builtin.debug:
        msg: "{{ lacp_groups | selectattr('interfaces', 'contains', 'em1') | map(attribute='master') | first }}"

How it works

contains is the reverse of the Jinja in test. selectattr keeps groups whose interfaces list includes em1. map then first returns that group's master value.

When to use it

  • Selecting a record whose interfaces or tags list includes a name
  • Rejecting list items that already have a value

Requirements

  • Ansible: >=2.14

Validation

  • Syntax validated
  • Not execution-tested
  • Last verified 2026-09-18

Notes

For a simple membership check use in: 'em1' in interfaces. Use is contains when the test must be the filter name in selectattr. Added in Ansible 2.8.

Reference

Built for every Ansible use case in every organization

BacklogZero can generate this kind of automation in your environment, just like it did here.

Get BacklogZero today →

Related guides

← Back to Ansible in a Minute

Use contains to test if a list has a value · Level Up Labs