I'm sure there's probably a way to do it in one play with a lot of fancy jinja2 commands, but you may be less likely to go insane by using your own custom plugin. If you create a 'filter_plugins' directory in the root of the folder you keep your ansible scripts, Ansible will automagically find them. Here's my 'filter_plugins/contains_any.py' file:
# lambda gratefully 'borrowed' from:
# https://stackoverflow.com/questions/10668282/one-liner-to-check-if-at-least-one-item-in-list-exists-in-another-list
contains_any = lambda a, b: any(i in b for i in a)
class FilterModule(object):
def filters(self):
return {
'contains_any': contains_any
}
In your playbook, you can use the 'set_fact' module to set the the True/False value based on whether there are any matches between the lists. When you pipe 'the_list' into 'contains_any', it automatically sets 'the_list' as the first variable, so you only need to explicitly pass 'the_other_list':
---
- hosts: localhost
vars:
the_list: [jane, bill, janet, suzy]
the_other_list: [jane, steve, bob, sam, turkey]
tasks:
- set_fact:
any_matches: "{{ the_list | contains_any(the_other_list) }}"
- debug: msg="Success!"
when: any_matches
Here's the output:
PLAY ***************************************************************************
TASK [setup] *******************************************************************
ok: [localhost]
TASK [set_fact] ****************************************************************
ok: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": "Success!"
}
PLAY RECAP *********************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0
EDIT: Thanks to this answer for the lambda function