Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate set difference using jinja2 (in ansible)

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?

like image 593
2rs2ts Avatar asked Oct 18 '16 18:10

2rs2ts


2 Answers

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

like image 99
Adrien Clerc Avatar answered Sep 20 '22 09:09

Adrien Clerc


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 }}"
like image 30
2rs2ts Avatar answered Sep 20 '22 09:09

2rs2ts