My file structure is like below
[root@test exim]# cat exim.json
{
"general": {
"max_hourly_email": 0,
"max_notify_email": 0,
"enable_mail_retry": "1",
"mail_retry": 15,
"enable_roundcube": "1",
"default_quota_val": 32768,
"default_quota": "1",
"eximmailtrap": "1",
"no_local_emailing": "0",
"dkim_selector": "x",
"disable_ipv6": "0",
"custom_mailips": "0",
"message_linelength_limit": 2048
I want to change the value of "max_hourly_email" and "max_notify_email"
**I am trying to change the valued using following method:
**
- name: Set Max hourly emails per domain
lineinfile:
path: /var/webuzo/conf/exim/exim.json
regexp: 'max_hourly_email'
line: ' "max_hourly_email": 200,'
state: present
It is changing the value but breaking the file sturcture like below
[root@test exim]# cat exim.json
{
"general": {
**"max_hourly_email": 200,**
"max_notify_email": 0,
"enable_mail_retry": "1",
"mail_retry": 15,
"enable_roundcube": "1",
"default_quota_val": 32768,
"default_quota": "1",
"eximmailtrap": "1",
"no_local_emailing": "0",
"dkim_selector": "x",
"disable_ipv6": "0",
"custom_mailips": "0",
"message_linelength_limit": 2048
How may I change the values using ansible without breaking the structure.
Thanks.
2
Answers
Given the file with the sorted dictionary for simpler comparison
lineinfile
Create a dictionary with the updates. For example, if you want to keep the double quotes make them part of the string
The task below will update existing keys, but won’t add a new one
gives when running with options –check –diff
template
There is a more flexible option of combining the dictionaries and using a template. Remove the extra quotation
combine the dictionaries
gives when running with options –check –diff
Notes
Example of a complete playbook for testing
Above answer by Vladimir is quite comprehensive , adding to above I have written a simple playbook using jinja expression which is easy to understand.
exim.j2
Using the above jinja file in the below playbook
Below is the output final.txt that is produced as desired.