'Ansible pretty print json

when I'm running my playbook I get the debug output in the correct json format I would want it

"ansible_facts": {
    "routes": [
        {
            "subnet": "10.0.0.0/24"
        },
        {
            "subnet": "10.0.1.0/24"
        }
    ]
},

but when I export it to a file using the local_action directive it displays like this

[{"subnet": "10.0.0.0/24"}, {"subnet": "10.0.1.0/24"}

Is there any working pretty print module or in Ansible which would export my file in the same way as I see it in the debug messages?

Thanks!



Solution 1:[1]

Not exactly the output you get on screen, but you could use a template task to print the variable, after passing it through a to_nice_json filter. Example:

---
- hosts: localhost
  gather_facts: false
  vars:
    my_ansible_facts:
      routes:
      - subnet: 10.0.0.0/24
      - subnet: 10.0.1.0/24

  tasks:
  - template: src=nice_yaml_filter.j2 dest=/tmp/nice_yaml_filter.out

Please note that i am not using the same variable as you are, just a my_ansible_facts variable that i populated.

And the template file's contents, nice_yaml_filter.j2:

{{ my_ansible_facts | to_nice_json }}

Result:

[http_offline@greenhat-32 ANSIBLE_TESTS]$ cat /tmp/nice_yaml_filter.out 
{
    "routes": [
        {
            "subnet": "10.0.0.0/24"
        },
        {
            "subnet": "10.0.1.0/24"
        }
    ]
}[http_offline@greenhat-32 ANSIBLE_TESTS]$ 

cheers

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ilias-sp