Edit JSON config file using ansible "lineinfile" module

4,341 views
Skip to first unread message

Guillaume DEDRIE

unread,
Jan 5, 2014, 8:12:38 AM1/5/14
to ansible...@googlegroups.com
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

Michael DeHaan

unread,
Jan 5, 2014, 1:56:03 PM1/5/14
to ansible...@googlegroups.com
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.


--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



--
Michael DeHaan <mic...@ansibleworks.com>
CTO, AnsibleWorks, Inc.
http://www.ansibleworks.com/

John Jarvis

unread,
Jan 5, 2014, 8:59:12 PM1/5/14
to ansible...@googlegroups.com
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 }}

Guillaume DEDRIE

unread,
Jan 6, 2014, 4:48:04 PM1/6/14
to ansible...@googlegroups.com
Thanks Michael and John for your answers !

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

Thanks a lot,
Guillaume
Reply all
Reply to author
Forward
0 new messages