danielhklein danielhklein - 4 months ago 42
YAML Question

YAML - intersection of arrays

In the main.yaml file of an Ansible playbook, I have the following play:

- name: configure client
include: client-configuration.yml
when: "'a' in group_names or 'b' in group_names or 'c' in group_names or 'd' in group_names or 'e' in group_names or 'f' in group_names or 'g' in group_names or 'h' in group_names or 'i' in group_names or 'j' in group_names..."


this continues for a while. Ideally, I would like to create an array that contains a, b, c, etc. and returns true if the intersection of my array and group_names has >0 elements, and return false otherwise. Is there a way to do this?

Answer

To get the intersection of two lists use the intersect filter. To get the length of a list use the length filter.

Your condition then can look like this:

- name: configure client
  include: client-configuration.yml
  when: group_names | intersect(myList) | length