I am trying to write ansible code first time to handle json.
I have a file in my /home/ which has following json data.
here is the input json
"acl": [
{
"browse": true,
"create": false
},
{
"browse": false,
"create": true
}
],
"groups": [
{
"name": "abc",
"location": "texas"
},
{
"name": "def",
"location": "austin"
}
],
"users": [
{
"name": "admin",
"description": "administrator",
"password": "windows2011"
},
{
"name": "testuser",
"description": "guest",
"password": "testpassword"
}
]
}
I want to update password of the user in user’s object where name is admin
so i that output file has updated password for user admin. the output file should be located in /home/location with _updated.json extension.
the output json should like this
{
"acl": [
{
"browse": true,
"create": false
},
{
"browse": false,
"create": true
}
],
"groups": [
{
"name": "abc",
"location": "texas"
},
{
"name": "def",
"location": "austin"
}
],
"users": [
{
"name": "admin",
"description": "administrator",
"password": "updatedpassword"
},
{
"name": "testuser",
"description": "guest",
"password": "testpassword"
}
]
}
ansible code which i have written so far-
---
- name: Update admin user password in JSON file
hosts: localhost
gather_facts: no
tasks:
- name: Read the JSON file
ansible.builtin.command:
cmd: cat /home/conf.json
register: json_content
Thank you.
2
Answers
What you can do is use the
template
module and use "variable interpolation" to put in the password you wish to use. First update yourconf.json
file:Then update your Ansible script to replace the variable with the new password:
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_module.html
You could also do the same with the
testuser
account by replacing the password with{{ testuser_password }}
and then adding the variable and value to the Ansible script.and read it into a dictionary
gives
and merge them
gives
gives
gives what you want
Example of a complete playbook for testing