[英]Ansible: set_fact on a json object
I have a json object in an Ansible variable ( my_var
), which contains values similar to the following: 我在Ansible变量( my_var
)中有一个json对象,该对象包含类似于以下内容的值:
{
"Enabled": "true"
"SomeOtherVariable": "value"
}
I want to modify the value of Enabled
in my_var
and have tried the following: 我想在my_var
修改Enabled
的值,并尝试了以下方法:
set_fact:
my_var.Enabled: false
and 和
set_fact:
my_var['Enabled']: false
Which both give errors similar to: 两者都给出类似于以下内容的错误:
"The variable name 'my_var.Enabled' is not valid. Variables must start with a letter or underscore character, and contain only letters, numbers and underscores." “变量名'my_var.Enabled'无效。变量必须以字母或下划线字符开头,并且只能包含字母,数字和下划线。”
Can this be done with set_fact or is there some other way of achieving this? 可以使用set_fact完成此操作,还是有其他方法可以实现此目的?
this was my solution - probably not the most eloquent: 这是我的解决方案-可能不是最雄辩的:
- set_fact:
my_temp_enabled_var: '{ "Enabled": "false" }'
- set_fact:
my_temp_enabled_var: "{{ my_temp_enabled_var | from_json }}"
- set_fact:
my_var: "{{ my_var | combine(my_temp_enabled_var) }}"
You can create a new dictionary with a Jinja2 template: 您可以使用Jinja2模板创建新字典:
---
- hosts: localhost
gather_facts: no
connection: local
vars:
my_var:
Enabled: true
SomeOtherVariable: value
tasks:
- debug:
var: my_var
- set_fact:
my_var: '{ "Enabled": false, "SomeOtherVariable": "{{ my_var.SomeOtherVariable }}" }'
- debug:
var: my_var
And the result: 结果:
TASK [debug] *******************************************************************
ok: [localhost] => {
"my_var": {
"Enabled": true,
"SomeOtherVariable": "value"
}
}
TASK [set_fact] ****************************************************************
ok: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => {
"my_var": {
"Enabled": false,
"SomeOtherVariable": "value"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.