Nikesh Jauhari
Nikesh Jauhari

Reputation: 245

Create Json file

How can I create a new JSON file based on the input key-value pair?
The input key/value pair can be of any number.

User input:

filename: myfile
json:
  key1: value1
  key2: value2

Upvotes: 2

Views: 1790

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 67959

The task

    - copy:
        content: "{{ {item: lookup('vars', item.var)}|to_nice_json }}"
        dest: "{{ item.filename }}.json"
      loop:
        - var: json
          filename: myfile

gives

shell> cat myfile.json 
{
    "json": {
        "key1": "value1",
        "key2": "value2"
    }
}

It's possible to loop more variables. For example,

  vars:
    filename: myfile
    json1:
      key1: value1
      key2: value2
    json2:
      key3: value3
      key4: value4

  tasks:
    - copy:
        content: |
          {% for item in my_vars %}
          {{ {item: lookup('vars', item)}|to_nice_json }}
          {% endfor %}
        dest: "{{ filename }}.json"
      vars:
        my_vars:
          - json1
          - json2

gives

shell> cat myfile.json 
{
    "json1": {
        "key1": "value1",
        "key2": "value2"
    }
}
{
    "json2": {
        "key3": "value3",
        "key4": "value4"
    }
}

Upvotes: 2

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39069

There is a to_json Jinja filter in Ansible that can do just that for you.

Use it in the content attribute of your copy task and you should have your desired output.

Given the playbook

- hosts: localhost
  gather_facts: no

  vars:
    filename: myfile
    json:
      key1: value1
      key2: value2

  tasks:
    - copy:
        content: "{{ json | to_json }}"
        dest: "{{ filename }}.json"

Which gives the recap

PLAY [localhost] ***************************************************************

TASK [copy] ********************************************************************
changed: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

And generate the files myfile.json, containing

{"key1": "value1", "key2": "value2"}

Upvotes: 3

Related Questions