# Test for set membership from a set?

**URL:** <https://forum.ansible.com/t/test-for-set-membership-from-a-set/25185>\
**Category:** Ansible Project\
**Created:** [August 4, 2017, 8:55pm UTC](https://forum.ansible.com/t/test-for-set-membership-from-a-set/25185 "2017-08-04T20:55:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tim\_Gaastra](https://avatars.discourse-cdn.com/v4/letter/t/ba8739/32.png) [@Tim\_Gaastra](https://forum.ansible.com/u/Tim_Gaastra)\
**Post date:** [August 4, 2017, 8:55pm UTC](https://forum.ansible.com/t/test-for-set-membership-from-a-set/25185/1 "2017-08-04T20:55:15Z")

</div>

Is there any way in Ansible to succinctly test for set membership in a list, from a list?

An example in psuedo-Ansible code:

users:

- name: Jim  
employee\_roles:
- Admin
- name: Bob  
employee\_roles:
- DBA
- name: Suz  
employee\_roles:
- Developer
- name: Kev  
employee\_roles:
- DBA
- Developer

Then, in group vars for a set of hosts:

group-a

---

<div class="post-metadata">

**Author:** ![tkuratom](https://avatars.discourse-cdn.com/v4/letter/t/b19c9b/32.png) [@tkuratom](https://forum.ansible.com/u/tkuratom)\
**Post date:** [August 5, 2017, 5:26am UTC](https://forum.ansible.com/t/test-for-set-membership-from-a-set/25185/2 "2017-08-05T05:26:47Z")

</div>

I think the intersect() filter is what you are looking for:  
[http://docs.ansible.com/ansible/latest/playbooks\_filters.html#set-theory-filters](http://docs.ansible.com/ansible/latest/playbooks_filters.html#set-theory-filters)

Here’s what I think (untested) your task would look like:

tasks:

- name: Test

debug:

msg: “Do a thing to {{ item }} on {{ inventory\_hostname }}”

with\_items: “{{ users }}”

when: item.employee\_roles | intersect(hostvars[inventory\_hostname].active\_system\_roles)

-Toshio

---

<div class="post-metadata">

**Author:** ![Tim\_Gaastra](https://avatars.discourse-cdn.com/v4/letter/t/ba8739/32.png) [@Tim\_Gaastra](https://forum.ansible.com/u/Tim_Gaastra)\
**Post date:** [August 7, 2017, 6:01pm UTC](https://forum.ansible.com/t/test-for-set-membership-from-a-set/25185/3 "2017-08-07T18:01:36Z")

</div>

This does seem to do the trick. Now I just need to experiment with it a bit to see how it works with “with\_subelements” type iterators.
