Alexander D
Alexander D

Reputation: 101

Taking an ansible variable as a json one liner?

I'd like to populate a configuration file using Ansible and the template module. I'll be receiving the json payload from another system as a one liner in this format..

[
    {
        "customer": "customer_name",
        "license_type": "eval",
        "customFields": {
            "test": 1234
        }
    },
    {
        "customer": "customer_name",
        "license_type": "eval",
        "customFields": {
            "test": 123
        }
    }
]

Compressed as a one-liner:

[ { "customer": "customer_name", "license_type": "eval", "customFields": { "test": 1234 } }, { "customer": "customer_name", "license_type": "eval", "customFields": { "test": 123 } } ]

In my ansible I've set a variable (entire_lic) to be that entire one-liner and then in the template module I have a template called license.conf with:

{{ entire_lic }}

This works, however it's not pretty printed to nice readable json. Is there anyway I can do this? I've tried

{{ entire_lic | to_nice_json }}

but that doesnt seem to work. Any help would be greatly appreciated!

Upvotes: 1

Views: 905

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68034

Q: "It's not pretty-printed to nice readable JSON. Is there any way I can do this?"

A: The playbook below does the job

shell> cat play.yml
- hosts: localhost
  vars:
    entire_lic: [{"customer": "customer_name", "license_type": "eval", "customFields": {"test": 1234}}, {"customer": "customer_name", "license_type": "eval", "customFields": {"test": 123}}]
  tasks:
    - debug:
        var: entire_lic
    - template:
        src: license.conf.j2
        dest: license.conf
shell> cat license.conf.j2 
{{ entire_lic | to_nice_json }}

gives

PLAY [localhost] ***

TASK [debug] ***
ok: [localhost] => {
    "entire_lic": [
        {
            "customFields": {
                "test": 1234
            }, 
            "customer": "customer_name", 
            "license_type": "eval"
        }, 
        {
            "customFields": {
                "test": 123
            }, 
            "customer": "customer_name", 
            "license_type": "eval"
        }
    ]
}

TASK [template] ***
changed: [localhost]

PLAY RECAP ***
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
shell> cat license.conf
[
    {
        "customFields": {
            "test": 1234
        },
        "customer": "customer_name",
        "license_type": "eval"
    },
    {
        "customFields": {
            "test": 123
        },
        "customer": "customer_name",
        "license_type": "eval"
    }
]

Upvotes: 2

Related Questions