Add a new key-value to a json file using Ansible

since the file is of json format, you could import the file to a variable, append the extra key:value pairs you want, and then write back to the filesystem.

here is a way to do it:

---
- hosts: localhost
  connection: local
  gather_facts: false
  vars:

  tasks:
  - name: load var from file
    include_vars:
      file: /tmp/var.json
      name: imported_var

  - debug:
      var: imported_var

  - name: append more key/values
    set_fact:
      imported_var: "{{ imported_var | default([]) | combine({ 'hello': 'world' }) }}"

  - debug:
      var: imported_var

  - name: write var to file
    copy: 
      content: "{{ imported_var | to_nice_json }}" 
      dest: /tmp/final.json

UPDATE:

as OP updated, the code should work towards remote host, in this case we cant use included_vars or lookups. We could use the slurp module.

NEW code for remote hosts:

---
- hosts: greenhat
  # connection: local
  gather_facts: false
  vars:

  tasks:
  - name: load var from file
    slurp:
      src: /tmp/var.json
    register: imported_var

  - debug:
      msg: "{{ imported_var.content|b64decode|from_json }}"

  - name: append more key/values
    set_fact:
      imported_var: "{{ imported_var.content|b64decode|from_json | default([]) | combine({ 'hello': 'world' }) }}"

  - debug:
      var: imported_var

  - name: write var to file
    copy: 
      content: "{{ imported_var | to_nice_json }}" 
      dest: /tmp/final.json

hope it helps

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)