我可以使用test.yml文件中的以下内容将2个列表合并在一起:
set_fact:
connectors: "{{containerports | default([]) }} + {{ newportslist }}"
在我的自定义事实JSON文件中产生了以下内容:
{
"containerports": [
{
"containername": "two",
"local_port_file": "10502",
"local_port_stream": "11502",
},
{
"containername": "five",
"local_port_file": "10503",
"local_port_stream": "11503",
}
]
}
Ansible中是否有一种方法可以删除整个列表{}?如果有的话,有没有办法根据字段名称将其删除?
理想情况下,我会有类似“删除列表的容器名称为”五”的列表,然后将我的事实文件更新为:
{
"containerports": [
{
"containername": "two",
"local_port_file": "10502",
"local_port_stream": "11502",
}
]
}
答案 0 :(得分:0)
继续阅读Jinja Filters。过滤器提供了各种处理数据的方法。 selectattr
过滤器是用于处理字典列表的常用过滤器,它会基于某些属性从列表中提取字典。有一个对应的rejectattr
,它提取所有不匹配的内容。因此,请尝试以下操作:
---
- hosts: localhost
connection: local
vars:
exclude_name: "two"
containerports:
- containername: "two"
local_port_file: "10502"
local_port_stream: "11502"
- containername: "three"
local_port_file: "10503"
local_port_stream: "11503"
- containername: "four"
local_port_file: "10504"
local_port_stream: "11504"
tasks:
- name: Extract all but dictionary called <exclude_name>
set_fact:
containerports: "{{ containerports | rejectattr('containername', 'match', exclude_name) | list }}"
- name: Display the result
debug:
var: containerports
结果:
TASK [Display the result] ********************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"containerports": [
{
"containername": "three",
"local_port_file": "10503",
"local_port_stream": "11503"
},
{
"containername": "four",
"local_port_file": "10504",
"local_port_stream": "11504"
}
]
}