Chapter #7: Jinja2 Templates
Learn how to use Jinja2 templating engine to carry out more involved and dynamic file modifications with Ansible.
In the previous tutorial about decision making in Ansible, you learned how to do simple file modifications by using the blockinfile or inline Ansible modules.
In this tutorial, you will learn how to use Jinja2 templating engine to carry out more involved and dynamic file modifications.
You will learn how to access variables and facts in Jinja2 templates. Furthermore, you will learn how to use conditional statements and loop structures in Jinja2.
To try the examples in this tutorial, you should follow the entire RHCE Ansible tutorial series in the correct order.
Accessing Variables in Jinja2
Ansible will look for jinja2 template files in your project directory or in a directory named templates under your project directory.
Letβs create a templates directory to keep thing cleaner and more organized:
[elliot@control plays]$ mkdir templates
[elliot@control plays]$ cd templates/
Now create your first Jinja2 template with the name index.j2:
[elliot@control templates]$ cat index.j2
A message from {{ inventory_hostname }}
{{ webserver_message }}
Notice that Jinja2 template filenames must end with the .j2 extension.
The inventory_hostname is another Ansible built-in (aka special or magic) variable that references that βcurrentβ host being iterated over in the play. The webserver_message is a variable that you will define in your playbook.
Now go one step back to your project directory and create the following check-apache.yml:
A Linux sysadmin who likes to code for fun. I have authored Learn Linux Quickly book to help people learn Linux easily. I also like watching the NBA and going for a cruise with my skateboard.