Modify JSON in Ansible
Not a direct answer to your question about the error with modify_json
but a working solution.
I would go with jq for that. jq
is a lightweight and flexible command-line JSON processor and available for nearly every Linux distribution. When not, use the prebuilt binaries that come without dependencies.
As the website states:
jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.
I shrinked your play to a minimal working solution with the same result. The jq
executable must be in the PATH
of the system it is running on. Feel free to customize it to your needs.
---
- name: Sync Power Schedules From Database to Survey Spec
hosts: localhost
gather_facts: no
vars:
choices_key: ".spec[6].choices"
choices_value: "23:00-02:00\n02:00-04:00\n04:00-06:00\n00:00-04:00"
json_file: "{{playbook_dir}}/s.json"
tasks:
- name: "modify json"
command: >
jq "{{choices_key}}=\"{{choices_value}}\"" "{{json_file}}"
register: json
- debug:
var: json.stdout
I think this is more elegant as the solution with the extra json_modify.py
module. For more information on jq
please see the manual page.