1. Templates¶
1.1. Why?¶
A Jinja template is simply a text file.
Jinja can generate any text-based format (HTML, XML, CSV, LaTeX, etc.)
A Jinja template doesn’t need to have a specific extension:
.html
,.xml
, or any other extension is just fine
1.2. Syntax¶
Syntax |
Description |
---|---|
|
Statements |
|
Expressions to print to the template output |
|
Comments not included in the template output |
|
Line Statements |
{% for page in user.get_created_pages() %}
...
{% endfor %}
1.3. Example¶
1.3.1. List hosts¶
{% for host in groups['all'] %}
{{ hostvars[host]['ansible_' + iface].ipv4.address }} {{ host }}
{% endfor %}
1.3.2. List users¶
<h1>List of users</h1>
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Role</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.first_name }}</td>
<td>{{ user.last_name }}</td>
{% if user.role == 'admin' %}
<td>Administrator</td>
{% else %}
<td>User</td>
{% endif %}
</tr>
{% endfor %}
<tbody>
</table>
1.4. Best practices¶
Ansible uses Jinja2
Jinja2 is powerful. Don't have to use all of it
Templates should be simple
Avoid variable substitution
Avoid setting variables in template
As few Conditionals as possible (do not nest)
Avoid conditional logic based on hostnames
Simple control structures/iterations
Design for your usecase (do not generalize)
Avoid complex iteration conditions
Label template output files as being generated by Ansible (warn not to edit manually)
Consider using
ansible_managed**
variable with the comment filter (it will put date and some other info)
{{ ansible_managed | comment }}