Edit JSON config file using ansible "lineinfile" module

Hi,
I’m looking for some help.

I’m trying to edit with “lineinfile” module a JSON config file:

  • name: Task
    lineinfile:
    dest=/etc/pkg/settings.json
    state=present
    regexp=‘{{ item.key }}’
    line=‘“{{ item.key }}”: {{ item.value }}’
    with_items:
  • { key: ‘setting1’, value: ‘true’ }
  • { key: ‘setting2’, value: ‘“value2”’ }

But, ansible return an error:

Note: The error may actually appear before this position: line x, column y

regexp=‘{{ item.key }}’
line=‘“{{ item.key }}”: {{ item.value }},’
^
This one looks easy to fix. YAML thought it was looking for the start of a
hash/dictionary and was confused to see a second “{”. Most likely this was
meant to be an ansible template evaluation instead, so we have to give the
parser a small hint that we wanted a string instead. The solution here is to
just quote the entire value.

For instance, if the original line was:

app_path: {{ base_path }}/foo

It should be written as:

app_path: “{{ base_path }}/foo”

Ansible failed to complete successfully. Any error output should be
visible above. Please fix these errors and try again.

I get an hotfix, using this template of key/value format:

  • {key: ‘“setting1”:’, value: true}
  • {key: ‘“setting2”:’, value: ‘“value2”’}

Is there another way to do this?

Regards,
Guillaume

That’s quite unsafe, JSON is not line oriented.

It would probably be better to just template out the file to be like you want it to be.

Since templating json can get messy another way to go about this is to
take your json configuration, express it as yaml in a var in ansible
and then do this in your template:

{{ app_settings | to_nice_json }}

Thanks Michael and John for your answers !

I’ll use template module instead (you convince me !).

Thanks a lot,
Guillaume