Ansible - how to remove an item from a list?

I would like to remove an item from a list based on another list.

"my_list_one": [ "item1", "item2", "item3" ] } 

My second list:

 "my_list_two": [ "item3" ] } 

How to remove "item3" from this list to establish a new fact?
I tried using '-' and this:

 set_fact: "{{ my_list_one | union(my_list_two) }}" 

Final goal:

 "my_list_one": [ "item1", "item2" ] } 
+5
source share
2 answers

Use difference not union :

 {{ my_list_one | difference(my_list_two) }} 

An example of a game book (note that you must also specify the name of the set_fact variable):

 --- - hosts: localhost connection: local vars: my_list_one: - item1 - item2 - item3 my_list_two: - item3 tasks: - set_fact: my_list_one: "{{ my_list_one | difference(my_list_two) }}" - debug: var=my_list_one 

Result (excerpt):

 TASK [debug] ******************************************************************* ok: [localhost] => { "my_list_one": [ "item1", "item2" ] } 
+8
source

Ansible - Set Model Filters

To get the difference in 2 lists (items from 1 that don't exist in 2):

 {{ list1 | difference(list2) }} 

Note: order matters, so you want {{ my_list_one | difference(my_list_two) }} {{ my_list_one | difference(my_list_two) }}


Since this is just a Jinja2 template, in pure Python, list - list is undefined.

 In [1]: list1 = [1, 2, 3] In [2]: list2 = [3] In [3]: list1 - list2 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-a683b4e3266d> in <module>() ----> 1 list1 - list2 TypeError: unsupported operand type(s) for -: 'list' and 'list' 

Instead, you can browse the list

 In [5]: [i for i in list1 if i not in list2] Out[5]: [1, 2] 
+1
source

Source: https://habr.com/ru/post/1260693/


All Articles