Separating Code and Data
Chapter 7
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
port = {{port}}
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 }}
apache_port = 80 apache_user = httpd conn = 1024
code
templates tasks
vars facts
data
Way to generate dynamic configurations
Ansible uses Jinja2 template engine
Along with Variables, can be used to create flexible roles
config => template
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/
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 %}
{{ 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 %}
Provide the properties
Can be defined from multiple places
Get merged at the run time, and injected into templates/tasks
Precedence Rules Apply
Role Default Vars
Inventory Vars : hostvars, groupvars
Playbook Vars
Role Vars
Extra Vars at the runtime (-e switch)
port
port1
mysql_port
mysql: port: 3306 user: mysql server: true
{{ port }}
{{ port1 }}
{{ mysql_port }}
{{ mysql[port] }}
{{ mysql.port }}
or
-e switch
role vars
playbook vars
host vars
group vars
role defaults