Write output of ansible task to file in proper JSON format

10,786

There is no ansible json module for doing this. But you can use third-party modules like ansible-jsonpatch for this.

Share:
10,786

Related videos on Youtube

Quijote
Author by

Quijote

Updated on June 04, 2022

Comments

  • Quijote
    Quijote almost 2 years

    I'm trying to write shell task output to json, but I have the problem of parsing it in a valid one json file.

    This is example of shell task output: {"firstname": "John", "lastname": "Smith", "user": "john"}

    - name: 'Execute script'
      shell: /tmp/script.sh
      register: script_output
    
    - name: 'Output to json'
      local_action:
        module: lineinfile
        dest: output.json
        line: '{{ script_output.stdout }}'
        create: yes
    

    After playbook execution, the json file has the following content:

    {"firstname": "John", "lastname": "Smith", "user": "john"}
    {"firstname": "John", "lastname": "Smith", "user": "john"}
    {"firstname": "John", "lastname": "Smith", "user": "john"}
    

    How can I format the output in the json valid format as attached?

    [
        {"firstname": "John", "lastname": "Smith", "user": "john"},
        {"firstname": "John", "lastname": "Smith", "user": "john"},
        {"firstname": "John", "lastname": "Smith", "user": "john"}
    ]