I have a simple json that looks like this:
{
"aaa": "true",
"bbb": "false",
"ccc": "true"
}
I would like enable ‘bbb’ value using ansible. Here is my playbook:
---
- hosts: "{{hosts}}"
remote_user: 'centos'
gather_facts: yes
become: yes
tasks:
- name: Load current facts
slurp:
path: "/tmp/file.json"
register: facts
- name: Enable fact
set_fact:
facts: "{{ facts | combine({ 'bbb': 'true' }) }}"
Nothing happen when i run this playbook, and the json file stays the same. What could be the issue?
2
Answers
You’ve got a few problems. First, you’ll want to inspect the content of the
facts
variable after yourLoad current facts
task has completed:This will show you that the contents of your
facts
variable is not what you think:To actual get the data from your JSON file, you would need to base64-decode the
content
key:Which gets you:
Putting that together gives us a playbook that looks something like this:
Which will output:
The
set_fact
simply creates an Ansible variable. If your goal is to actually modify/tmp/file.json
, you will need to add a task to write out the modified data to that file. Something like:Q: "I would like to enable ‘bbb’ value … the JSON file stays the same."
A: Use replace to modify the file. For example
gives