Calculate set difference using jinja2 (in ansible)
<p>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 <code>set</code> data structure. Here's what I was trying to do:</p>

<pre><code>- set_fact:
    difference: "{{ (set(listA) - set(listB)).pop() }}"
</code></pre>

<p>But I get an error saying <code>'set' is undefined</code>. 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?</p>

<p>Turns out there is a <a href="http://docs.ansible.com/ansible/playbooks_filters.html#set-theory-filters" rel="nofollow">built-in filter for this in ansible</a> (not in generic jinja) called <code>difference</code>.</p>

<p>This accomplishes what I was trying to do in my question:</p>

<pre><code>"{{ (listA | difference(listB)) | first }}"
</code></pre>

python ansible jinja2