How can I test jinja2 templates in ansible?

Question:

Sometimes I need to test some jinja2 templates that I use in my ansible roles. What is the simplest way for doing this?

For example, I have a template (test.j2):

and vars (in group_vars/all):

Answer:

At this time exists 4 different variants:

1_Online (using https://cryptic-cliffs-32040.herokuapp.com/)
Based on jinja2-live-parser code.

Example

2_Interactive (using python and library jinja2, PyYaml)

3_Ansible (using –check)

Create test playbook jinja2test.yml:

and run it:

sample output:

4_Ansible (using -m template)

Make a file called test.txt.j2

Call ansible like so:

It will output a file called test.txt in the current directory, which will contain the output of the evaluated test.txt.j2 template.

I understand this doesn’t directly use a vars file, but I think it’s the simplest way to test a template without using any external dependencies. Also, I believe there are some differences between what the jinja2 library provides and what ansible provides, so using ansible directly circumvents any discrepancies. When the JSON that is fed to --extra-vars satisfies your needs, you can convert it to YAML and be on your way.

Leave a Reply