Pages

Friday, 27 December 2019

EX294: Create and use templates to create customized configuration files

0 JinJa2 template

0.1 General introduction of JinJa2

JinJa2 is a popular template engine in the Python world.
Complete document about Jiaja2 can be found at https://jinja.palletsprojects.com/en/2.10.x/. Here we just give a simple introduction.

e.g.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>My Webpage</title>
</head>
<body>
    <ul id="navigation">
    {% for item in navigation %}
        <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
    {% endfor %}
    </ul>

    <h1>My Webpage</h1>
    {{ a_variable }}

    {# a comment #}
</body>
</html>

The default Jinja delimiters are configured as follows

0.2 Ansible playbooks inherently support the Jinja2 template

All Variables in Ansible can be used directly in JiaJa2 templates. A playbook file is a Jinja2 template itself, which means JinJa2 engine scans and processes the playbook file before its further actions.

1 In-playbook template with "copy" module

The "copy" module has an "content" attribute which can contain JinJa2 templates. JinJa templates are processed before "copy" module runs.

e.g.
config.j2


playbook.yml:

---
- hosts: localhost
  vars:
          listen_port: 80
          listen_ip: 0.0.0.0
  tasks:
          - name: copy test
            copy:
                    dest: /tmp/config.ini
                    content: >
                            IP: {{ listen_ip }}
                            PORT: {{ listen_port }}

 Unfortunately, the "copy" module doesn't support JinJa by itself, so JinJa2 templates cannot be in a source file to be copied. That's why the "template" module was developed.

2 Template files with "template" module

Unlike "copy", the "template" module uses the Jinja2 engine to scan and process its source file.
"template" module can be thought of as a super "copy" even though it lacks some functions such as copying folder. Any variable visible to the task running "template" module can be used in the template file. In the following example, task variables and inventory variables are used.

$ cat playbook.yml
---
- hosts: localhost
  tasks:
          - name: copy test
            vars:
                    listen_port: 8088
                    listen_ip:
                        - 192.168.0.100
                        - 192.168.0.103
            template:
                    src: config.j2
                    dest: /tmp/config.ini

$ cat config.j2
hostname: {{ inventory_hostname }}
{% for ip in listen_ip %}
Ip: {{ ip }}
{% endfor %}
Port: {{ listen_port }}

$ ansible-playbook playbook.yml
$ cat /tmp/config.ini
hostname: localhost
Ip: 192.168.0.100
Ip: 192.168.0.103
Port: 8088


No comments:

Post a Comment