The module template is helpful to create contents in the hosts. Jinja allows work by creating dynamically contents as the follows examples.
Variables Definitions
{{ ansible_user_dir }} {{ ansible_user_id }}
NOTE: The above example is using the facts variables which can be obtained by the command “ansible <host> -m setup”. For further information check the Ansible facts post.
Loops
{% for item in books %}
{{ item }}
{% endfor %}
{% for mybook in books if not mybook == "ansible in action"%}
{{ loop.index }} - {{ mybook }}
{% endfor %}
Conditionals
{% if ok %}
{{ result }}
{% endif %}
Changing the output format
{{ output | to_json }} # To print output in the json format {{ output | to_yaml }} # To print output in the yaml format
{{ output | to_nice_json }} #To print pretty in the json format {{ output | to_nice_yaml }} #To print pretty in the yam format
{{ output | from_json }} # To parse from json {{ output | from_yaml }} # To parse from yamls
Example of Usage
Following an example over how it can be used.
$cat users.j2The Ansible user {{ ansible_user_dir }} has the ID {{ansible_user_id }}.
Then, the above jinja file can be used with the module templates to add a file with this content in all hosts defined in the inventory as defined in the following playbook which is an example.
---
- hosts: all
tasks:
- template:
src: users.j2
dest: /tmp/user
owner: root
group: root
mode: 0755
So, if the above playbook is executed then all hosts will have a file created by the Jinja template file in the path /tmp/user. The file will be created with the owner root and will have the permission 0755 as described on it.
For further information see the following references.