Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible - how to remove an item from a list?

I'd 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 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.

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

End goal:

"my_list_one": [
  "item1",
  "item2"
]
like image 792
Kevin C Avatar asked Dec 02 '16 08:12

Kevin C


2 Answers

Use difference not union:

{{ my_list_one | difference(my_list_two) }}

An example playbook (note that you must also provide variable name to set_fact):

---
- 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):

TASK [debug] *******************************************************************
ok: [localhost] => {
    "my_list_one": [
        "item1",
        "item2"
    ]
}
like image 74
techraf Avatar answered Nov 14 '22 20:11

techraf


Ansible - Set Theory Filters

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

{{ list1 | difference(list2) }}

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


Since it's just a Jinja2 template, in pure Python, list - list is not defined.

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 do list-comprehension

In [5]: [i for i in list1 if i not in list2]
Out[5]: [1, 2]
like image 5
OneCricketeer Avatar answered Nov 14 '22 21:11

OneCricketeer