Question:
I’d like to remove an item from a list, based on another list.
1 2 3 4 5 6 |
"my_list_one": [ "item1", "item2", "item3" ] |
My second list:
1 2 3 4 |
"my_list_two": [ "item3" ] |
How do I remove ‘item3’ from this list, to set a new fact?
I tried using ‘-‘ and union, but this does not end in the desired end result.
1 2 3 |
set_fact: my_list_one: "{{ my_list_one | union(my_list_two) }}" |
End goal:
1 2 3 4 5 |
"my_list_one": [ "item1", "item2" ] |
Answer:
Use difference
not union
:
1 2 |
{{ my_list_one | difference(my_list_two) }} |
An example playbook (note that you must also provide variable name to set_fact
):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
--- - 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 |
The result (excerpt):
1 2 3 4 5 6 7 8 |
TASK [debug] ******************************************************************* ok: [localhost] => { "my_list_one": [ "item1", "item2" ] } |