我想在嵌套字典中添加新值,并删除旧值。
这是我的parse.json文件。
{
"class": "Service_HTTPS",
"layer4": "tcp",
"profileTCP": {
"egress": {
"use": "/Common/Shared/f5-tcp-wan"
},
"ingress": {
"use": "/Common/Shared/f5-tcp-lan"
}
}
}这是我的脚本,它将增加新的值,但也是保留旧的值,我知道我使用的是recursive=True,但是没有这个命令,我就丢失了入口键。
这是我的剧本:
- set_fact:
json_file: "{{ lookup('file', 'parse.json') }}"
- set_fact:
json_file: "{{ json_file | combine( egress_modify, recursive=True) }}"
when: json_file['profileTCP']['egress'] is defined
vars:
egress_modify: "{{ json_file | combine({ 'profileTCP': { 'egress': { 'bigip': '/Common/' + json_file['profileTCP']['egress']['use'].split('/')[-1] } }}) }}"
- name: debug
debug:
msg: "{{ json_file }}"错误结果
ok: [localhost] => {
"msg": {
"class": "Service_HTTPS",
"layer4": "tcp",
"profileTCP": {
"egress": {
"bigip": "/Common/f5-tcp-wan",
"use": "/Common/Shared/f5-tcp-wan"
},
"ingress": {
"use": "/Common/Shared/f5-tcp-lan"
}
}
}
}但我想得到这个结果
ok: [localhost] => {
"msg": {
"class": "Service_HTTPS",
"layer4": "tcp",
"profileTCP": {
"egress": {
"bigip": "/Common/f5-tcp-wan",
},
"ingress": {
"use": "/Common/Shared/f5-tcp-lan"
}
}
}
}发布于 2022-05-14 03:20:40
dict是ansible中的"live“,所以您可以继续执行"set_fact:,循环:”业务,也可以一次性完成所有操作:
- set_fact:
json_file: >-
{%- set j = lookup('file', 'parse.json') | from_json -%}
{%- set tcp_egress_use = j.profileTCP.egress.pop('use') -%}
{%- set _ = j.profileTCP.egress.update({
'bigip': '/Common/' + tcp_egress_use.split('/')[-1]
}) -%}
{{ j }}产生
"json_file": {
"class": "Service_HTTPS",
"layer4": "tcp",
"profileTCP": {
"egress": {
"bigip": "/Common/f5-tcp-wan"
},
"ingress": {
"use": "/Common/Shared/f5-tcp-lan"
}
}
}https://stackoverflow.com/questions/72236031
复制相似问题