I have two lists of strings in my ansible playbook, and I'm trying to find the elements in list A that aren't in list B - a set difference. However, I don't seem to be able to access the python set
data structure. Here's what I was trying to do:
- set_fact:
difference: "{{ (set(listA) - set(listB)).pop() }}"
But I get an error saying 'set' is undefined
. Makes sense to me since it's not a variable but I don't know what else to do. How can I calculate the set difference of these two lists? Is it impossible with the stock jinja functionality in ansible?
In generic Jinja2, this can be achieved quite easily, combining the reject
filter with the in
test:
"{{ listA | reject('in', listB) | first }}"
This requires Jinja >= 2.10
Turns out there is a built-in filter for this in ansible (not in generic jinja) called difference
.
This accomplishes what I was trying to do in my question:
"{{ (listA | difference(listB)) | first }}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With