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):
{% if users is defined and users %}
{% for user in users %}{{ user }}
{% endfor %}
{% endif %}
and vars (in group_vars/all):
---
users:
- Mike
- Smith
- Klara
- Alex
You can use the debug module
At this time exists 4 different variants:
1_Online (using https://cryptic-cliffs-32040.herokuapp.com/)
Based on jinja2-live-parser code.
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) thanks for @artburkart
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 evaluatedtest.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.If you have a jinja2 template called
test.j2
and a vars file located atgroup_vars/all.yml
, then you can test the template with the following command:It will output a file called
test.txt
in the current directory, which will contain the output of the evaluatedtest.j2
template.I think this is the simplest way to test a template without using any external dependencies. Also, there are differences between what the jinja2 library provides and what ansible provides, so using ansible directly circumvents any discrepancies. It's also possible to test ad-hoc variables without making an additional vars file by using JSON: