I have a json object in an Ansible variable ( my_var
), which contains values similar to the following:
{
"Enabled": "true"
"SomeOtherVariable": "value"
}
I want to modify the value of Enabled
in my_var
and have tried the following:
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."
Can this be done with set_fact or is there some other way of achieving this?
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:
---
- 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"
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.