在Ansible中替换字典列表中的值
我正在尝试替换键"extension_last_heartbeat_time"的值,(日期),并带有静态字符串< LAST_HEARTBEAT_TIME>"在此字典列表中
I'm trying to replace the value of the key "extension_last_heartbeat_time" (date) with a static string "<LAST_HEARTBEAT_TIME>" in this list of dicts
[
{
"vcenter": "vcenter-A",
"vcenter_extension_info": [
{
"extension_company": "VMware Inc.",
"extension_key": "com.vmware.vim.sms",
"extension_label": "VMware vCenter Storage Monitoring Service",
"extension_last_heartbeat_time": "2020-11-03T09:05:41.676497+00:00",
"extension_type": "",
"extension_version": "5.5"
},
{
"extension_company": "VMware Inc.",
"extension_key": "com.vmware.vim.vsm",
"extension_last_heartbeat_time": "2020-11-03T09:05:41.678007+00:00",
"extension_type": "",
"extension_version": "6.5"
},
{
"extension_company": null,
"extension_key": "VirtualCenter",
"extension_last_heartbeat_time": "2020-11-03T09:05:41.684018+00:00",
"extension_type": "",
"extension_version": "1.0"
}
]
},
{
"vcenter": "vcenter-B",
"vcenter_extension_info": [
{
"extension_company": "VMware Inc.",
"extension_key": "com.vmware.vim.sms",
"extension_last_heartbeat_time": "2020-08-17T13:12:10.529370+00:00",
"extension_type": "",
"extension_version": "5.5"
},
{
"extension_company": "VMware Inc.",
"extension_key": "com.vmware.vim.vsm",
"extension_last_heartbeat_time": "2020-08-17T13:12:10.530946+00:00",
"extension_type": "",
"extension_version": "6.5"
},
{
"extension_company": null,
"extension_key": "VirtualCenter",
"extension_last_heartbeat_time": "2020-08-17T13:12:10.537281+00:00",
"extension_version": "1.0"
}
]
}
]
我尝试过:
- 名称:匿名上次心跳时间set_fact:字典:"{{字典|map('regex_replace','[0-9] {4}-[0-9] {2}-[0-9] {2} T [0-9] {2}:[0-9] {2}:[0-9] {2}.*','< LAST_HEARTBEAT_TIME>')|列表}}''"
但是它会删除大部分数据
But it removes a big part of the data
Jinja2数据结构是实时的",因此它们在所有jinja2评估上下文中都可能发生突变.诀窍是(至少在本文结束时) set
语句创建了新的 local 变量,并且未分配用户可能期望的方式,从而导致了一些愚蠢的行为.这就是为什么必须使用 dict.update
作为覆盖此dict成员"的原因.解决方法
Jinja2 data structures are "live", so they are subject to mutation in all jinja2 evaluation contexts. The trick is that (at least as of this post) the set
statement creates new local variables, and does not assign the way a user might expect, leading to some silliness. That's why one must use dict.update
as a "overwrite this dict member" work-around
- set_fact:
# you didn't say what variable contained that outermost `list[dict]`
# so change that as needed
vcenter_data: |
{%- for i in vcenter_data -%}
{%- for e in i.vcenter_extension_info -%}
{%- set _ = e.update({
"extension_last_heartbeat_time": new_extension_last_heartbeat_time}) -%}
{%- endfor -%}
{%- endfor -%}
{{ vcenter_data }}
vars:
new_extension_last_heartbeat_time: '1111-22-33'