13. Templates

13.1. Introduction into Jinja 2

  • Jinja2 is a templating engine for python
  • Ansible is using the Jinja2 templating system
  • Loops, Filters and Conditionals are available in Jinja2

13.2. Benefits of templates

  • Templates allow you to generate configuration files with different variable values

  • conditionals and loops can also be used in templates

  • you can store one template in source control that applies to many different environments

  • some use-cases could be

    • different values for environments e.g test / prod
    • different values for tiers e.g frontend / backend

13.2.1. How to use templates

  • Create a templates folder in your role directory
  • Place your file in the templates directory
  • it’s recommended to use the file extension .j2
  • in the template use variables with brackets {{ }}
# file: templates/httpd.conf.j2
This is a config file.
My first variable is a fact.
I'm a {{ ansible_os_family }} server!
  • create a task and use the template module
- template:
    src: httpd.conf.j2
    dest: /etc/httpd.conf
    owner: root
    group: root
    mode: 0644

Hint

The best way is to name your source file like destination file with the additional j2 file extension -> httpd.conf.j2

13.2.2. ansible_managed Header

  • a string that can be inserted into files written by Ansible’s config templating system
  • the string can be changed in the Ansible configuration file
  • should be used to tell users, that a file is managed by Ansible
ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host}

Hint

Per default is a date in the string, so the template will be reported changed each time as the date is updated.

13.2.3. Loops and Conditionals

  • you can use loops and if statements in templates
# loop
{% for user in sudo_users %}
{{ user }} ALL=(ALL) NOPASSWD: ALL
{% endfor %}

# conditional
{% if sudo_rsync %}
{{ user }} ALL=(ALL) NOPASSWD: /bin/rsync
{% endif %}

Hint

Ansible allows Jinja2 loops and conditionals in templates, but not in playbooks. Ansible playbooks are pure machine-parseable YAML.

13.3. copy vs template

  • copy the file 1:1 on the managed host
  • template module is evaluated by jinja2 -> variables, loops and conditionals can be used
  • place the ansible_managed header into your templates

13.4. Jinja2 Filters

  • there are some useful filters available

  • filters can be combined

    • {{ list | join(" ") }} (concenate lists)
    • {{ myvar | upper }} or lower
    • {{ myvar | max }} or min
    • {{ list | unique }}
    • {{ list | random }}
    • {{ myvar | checksum }}
    • {{ path | basename }}
    • {{ lvsize | default('0.25G') }}
    • {{ ansible_managed | comment }}