我试图修改JSON文件中的几个值。最有效的方法似乎是使用update_fact模块,该模块需要输出到寄存器。我遇到的问题是我需要运行JSON查询来查找需要修改的数据。
当我尝试用update_fact修改json文件时,我想在一个update_fact块中使用json_query,这样我就不会有一个递归的寄存器名称,我必须在最后摆脱,但每次我尝试这个ansible都告诉我msg: 'template error while templating string: unexpected char ''?'' at 40. String: {{ jsondata.stigs[0].rules| json_query([?group_id==V-256376].comments)}}'
有没有更好的方法来做到这一点,而不必尝试和打破JSON文件完全分开,修改每个部分,并尝试把它放回一起。这样做的最终目标是修改一堆vule并将其输出到一个文件。
我的playbook
tasks:
- name: Read file directly into fact
set_fact:
jsondata: "{{ lookup('file', './files/U_VMW_vSphere_7-0_ESXi_V1R2_Manual_STIG.cklb') | from_json}}"
- debug:
msg: "{{ test.stigs[0].rules|json_query(query)}}"
vars:
groupid: 'V-256376'
query: "[?group_id=='{{ groupid }}'].discussion"
register: v256376
- name: update IP address
ansible.utils.update_fact:
updates:
- path: jsondata.target_data.ip_address
value: "10.10.10.10"
- path: jsondata.target_data.host_name
value: "{{ esxserver }}"
- path: "{{ jsondata.stigs[0].rules| json_query([?group_id==V-256376].comments)}}"
value: "this worked"
register: jsondata
字符串
编辑添加后续问题的mre
检查表json文件精简为2个示例
{
"stigs": [
{
"rules": [
{
"group_id": "V-256375",
"status": "not_reviewed",
"comments": "",
"finding_details": ""
},
{
"group_id": "V-256375",
"status": "not_reviewed",
"comments": "",
"finding_details": ""
}
}
}
型
这样做的目的是获取JSON文件,这是一个检查列表,并在服务器上运行它,以查看设置是否正确,然后获取这些设置的副本并将其输出回JSON文件,作为设置正确的证据。很长一段路要说这是为了STIG验证。
对于每个group_id,我将需要进行一个API调用来检查,然后将状态字段更改为open或not_a_finding,然后在注解/finding_details中填写API调用的输出。
我们的想法是将变量更新为gid_comments['V-256375']: "The UserVars.HostClientSessionTimeout is set to '{{ UserVarsHostClientSessionTimeout }}'"
或gid_comments['V-256375']: "The UserVars.HostClientSessionTimeout is set to 900"
,然后使用原始问题将其放回JSON文件中,以便安全人员可以打开和读取。
所以接下来的问题变成了我如何动态地将东西添加到gid_comments['V-256375']
字段中,因为ansible似乎不喜欢带有-
的变量。
1条答案
按热度按时间yruzcnhs1#
给定mre YAML数据进行测试(格式不重要)
字符串
读取文件
型
给
型
Q:“使用json_query更新事实"
从您的查询(如下)中可以看出,您希望在 stigs 中第一项的 rules 中为等于V-256376的 group_id 更新 comments
型
A:这是不可能的。参数路径说:
它应该是一个有效的Jinja参考。
您的 json_query 的结果不是有效的Jinja引用。相反,您可以使用更新创建一个结构。例如,字典
型
并使用它来更新事实。创建要更新的列表
型
给
型
现在,使用列表 stigs_0_rules 更新事实
型
给你想要的
型
用于测试的完整剧本示例
型