ansible/ansible — pull request #956 by tima (2012-08-28 22:40:19+00:00)
Title: Add tojson filter to jinja environment used by the template module.

A couple of weeks ago I wrote to the mailing list looking for a way to generate a report about the hosts using Ansible. With the introduction of the delegate_to and this one-line change the the jinja environment I figured out a way to do this by looking at Flask.

- name: facts dumper
hosts: nodes
tasks:
name: dump facts
action: template src=/path/to/hostvars.j2 dest=/path/to/dump/facts/$inventory_hostname
delegate_to: localhost

/path/to/hostvars.j2 would contain:

{{ hostvars[inventory_hostname]|tojson|safe }}

This passes the hostvars struct to a filter that is just an alias to json.dumps and write that to the dest.

Thinking about it now I suppose this would have made something work by creating two plays -- one that runs on all nodes and another locally that does a json dump of hostvars. I'd have one big file as opposed to one for each host.

While this is a pretty specific use case, I could see having json encoding support within ansible templates something that could come in handy.