简体   繁体   English

使用jinja2计算集合差异(在ansible中)

[英]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. 我的ansible playbook中有两个字符串列表,我试图找到列表A中不在列表B中的元素 - 一组差异。 However, I don't seem to be able to access the python set data structure. 但是,我似乎无法访问python set数据结构。 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 . 但是我得到一个错误,说'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? 在ansible中使用股票jinja功能是不可能的?

Turns out there is a built-in filter for this in ansible (not in generic jinja) called difference . 事实证明, 在ansible (不是通用的jinja)中有一个内置的过滤器称为difference

This accomplishes what I was trying to do in my question: 这完成了我在我的问题中尝试做的事情:

"{{ (listA | difference(listB)) | first }}"

In generic Jinja2, this can be achieved quite easily, combining the reject filter with the in test: 在通用Jinja2的,这可以很容易地实现,结合reject过滤器与in测试:

"{{ listA | reject('in', listB) | first }}"

This requires Jinja >= 2.10 这需要Jinja> = 2.10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM