Red Hat Ansible Engine has a number of modules that can be used to modify existing files. These include lineinfile and blockinfile, among others. However, they are not always easy to use effectively and correctly.
A much more powerful way to manage files is to template them. With this method, you can write a template configuration file that is automatically customized for the managed host when the file is deployed, using Ansible variables and facts. This can be easier to control and is less error-prone.
INTRODUCTION TO JINJA2
Ansible uses the Jinja2 templating system for template files. Ansible also uses Jinja2 syntax to reference variables in playbooks, so you already know a little bit about how to use it.
Using Delimiters
Variables and logic expressions are placed between tags, or delimiters. For example, Jinja2 templates use {% EXPR %} for expressions or logic (for example, loops), while {{ EXPR }} are used for outputting the results of an expression or a variable to the end user. The latter tag, when rendered, is replaced with a value or values, and are seen by the end user. Use {# COMMENT #} syntax to enclose comments that should not appear in the final file.
In the following example the first line includes a comment that will not be included in the final tile. The variable references in the second line are replaced with the values of the system facts being referenced
( /etc/hosts line #)
{{ ansible_facts.default_ipv4.address }}
{{ ansible_facts.hostname }}
TASK BY TRAINER:
- Create a template for the Message of the Day and include it in the motd.j2 file in the current working directory. Include the following variables in the template:
ansible_hostname – to retrieve the host name of the managed node
ansible_facts.default_ipv4.address – to retrieve the IP