问题
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"
}
]
}
]
I tried :
- name: anonymize last heartbeat time set_fact: dict: "{{ dict | 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>') | list }}"
But it removes a big part of the data
回答1:
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'
回答2:
One of the ways of resolving this is by using regex_replace. If the data is in the variable "vcenter_data" then the solution could look like this :
- name: anonymize instance uuid
set_fact:
vcenter_data: "{{ vcenter_data| regex_replace('[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}', '<INSTANCE_UUID>') }}"
来源:https://stackoverflow.com/questions/65953988/replace-value-in-list-of-dict-in-ansible