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.
---
- name: Find the LACP group that contains em1
hosts: all
gather_facts: false
vars:
lacp_groups:
- master: lacp0
interfaces:
- em1
- em2
- master: lacp1
interfaces:
- em3
- em4
tasks:
- name: Print the master for em1
ansible.builtin.debug:
msg: "{{ (lacp_groups | selectattr('interfaces', 'contains', 'em1') | first).master }}"How it works
contains is the reverse of the Jinja in test. Use it with selectattr, rejectattr, select, or reject when you filter a list of dictionaries by a nested list field.
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-17
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
- Testing if a list contains a value (Ansible docs)
Built for every Ansible use case in every organization
BacklogZero can generate this kind of automation in your environment, just like it did here.