Ansible: set_fact on a json object

23.1k Views Asked by At

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?

2

There are 2 best solutions below

1
Willem van Ketwich On BEST ANSWER

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) }}"
4
techraf On

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"
    }
}