Test for set membership from a set?

21 views
Skip to first unread message

Tim Gaastra

unread,
Aug 4, 2017, 4:55:15 PM8/4/17
to Ansible Project
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 
----------
active_system_roles:
   - Admin
   - DBA

group-b
----------
active_system_roles:
   - Admin
   - Developer

I'd like a task that could do something like (aware this isn't real code):

tasks:
   - name: Test
     debug:
         msg: "Do a thing to that user on this host"
     with_items: "{{ users }}"
     when: item.employee_roles in hostvars[inventory_hostname].active_system_roles

I.E. if any of the employee's roles are in the list of active_system_roles, do a thing to that user on that host.



Toshio Kuratomi

unread,
Aug 5, 2017, 1:27:00 AM8/5/17
to ansible...@googlegroups.com
I think the intersect() filter is what you are looking for:
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

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-project+unsubscribe@googlegroups.com.
To post to this group, send email to ansible-project@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/95025760-a26b-4a13-bdf4-60294f84d325%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Tim Gaastra

unread,
Aug 7, 2017, 2:01:36 PM8/7/17
to Ansible Project
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.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages