Templates and variables

Separating Code and Data

Chapter 7

CONCEPTS

  • Static Content Explosion
  • Code vs Data
  • Templates : Jinja2
    
  • Variables and Facts
  • Variable Precedence
httpd.dev.conf
httpd.stg.conf
httpd.prod.conf
port = 80
port = 8080
port = 9000

Static

Configs

port = {{port}}

dynamic

configs

httpd.conf.j2
port = 80
/etc/httpd/httpd.conf
apache_port = 80
roles/apache/default
apache_port = 8080
group_vars/staging
port = 80

templates

vars

port = {{ port }}
user = {{ user }}
conn = {{ conn }}

code vs data

apache_port = 80
apache_user = httpd
conn = 1024
code
templates

tasks
vars

facts
data

templates

  • Way to generate dynamic configurations
  • Ansible uses Jinja2 template engine
  • Along with Variables, can be used to create flexible roles
config => template

Jinja2

  • Python based template language 
  • Compiled just in time into python byte code
  • Fast
  • Commonly used by Python based Automation Tools such as Ansible, Fabric, Salt

http://jinja.pocoo.org/docs/dev/

Jinja2

  • Contains regular text with dynamic fragments, marked with special tags
  • Dynamic fragments are either variables or python code, which is executed at the run time, creating the resulting text files. 
  • Files are created using .j2 extensions and stored in templates directory inside roles

https://blog.codecentric.de/en/2014/08/jinja2-better-ansible-playbooks-templates/

{{   var   }}

{%  code   %}

Jinja2  tags

{{   var   }}

{%  code   %}

{{ mysql['config']['port'] }}

mysql.config.port
{% if mysql.config.port is defined %}
do something
{% endif %}

 

[mysqld]


{% if mysql.config.port is defined %}
port		 = {{ mysql['config']['port'] }}
{% endif %}

{% if mysql.config.pid is defined %}
datadir		 = {{ mysql['config']['datadir'] }}
{% endif %}

Jinja2  example

Variables

  • Provide the properties
  • Can be defined from multiple places
  • Get merged at the run time, and injected into templates/tasks
  • Precedence Rules Apply

variable types

User

Defined  

automatic

Facts

vars

user defined vars

  • Role Default Vars
  • Inventory Vars :  hostvars, groupvars
  • Playbook Vars
  • Role Vars 
  • Extra Vars at the runtime (-e switch)

accessing  vars

port
port1
mysql_port
mysql: 
  port: 3306 
  user: mysql
  server: true
{{ port }}
{{ port1 }}
{{ mysql_port }}
{{ mysql[port] }}
{{ mysql.port  }}

or

defining  vars

variable precedence

-e switch

role vars

playbook vars

host vars

group vars

role defaults

precedence

V2 Ansible 7: Templates and variables

By School of Devops

V2 Ansible 7: Templates and variables

Making Roles Sharable and Generic

  • 927