繁体   English   中英

Ansible - 如何从列表中删除项目?

[英]Ansible - how to remove an item from a list?

我想根据另一个列表从列表中删除一个项目。

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

我的第二个清单:

"my_list_two": [
    "item3"
] }

如何从此列表中删除“item3”以设置新事实?
我尝试使用' - '和这个:

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

最终目标:

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

使用difference而不是union

{{ my_list_one | difference(my_list_two) }}

示例剧本(请注意,您还必须为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

结果(摘录):

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

Ansible - 集理论滤波器

要获得2个列表(1中不存在于2中的项目)的区别:

 {{ list1 | difference(list2) }} 

注意:订单很重要,因此您需要{{ my_list_one | difference(my_list_two) }} {{ my_list_one | difference(my_list_two) }}


由于它只是一个Jinja2模板,在纯Python中, list - list没有定义。

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'

相反,你可以做列表理解

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

暂无
暂无

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

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