Ansible Template Tutorial

Author: R Zach Feeser

In the following youtube video, Zach Feeser demonstrates how to use the Ansible template module.

We have or three hosts–Fry, Bender, and Zoidberg–that we will be configuring. To do so, we will be running an Ansible playbook from our localhost (the Ansible controller), filling in the blanks of a jinja2 template.

ansible-template-module ansible-template-module

The six step process is as follows:

Step 1 - Define the template

By definition, a template is a document with intentional ommisions that will be filled in by the template module. Zach uses a configuration file as an example. Here is the file he used:

ship.cfg.j2

[default]
name = {{ shipname }} 
type = {{ shiptype }} 
engine type = {{ engines }}
Darkmatter maxcapacity = {{ dark Matter balls }} 
salesprice = {{ ship priceinbeans }} 
anti matter afterburner = true

Step 2 - Define the key-value pairs that will “fill in the blanks”

vars:
   shipname: "Bessie" 
   shiptype: "Intergalactic" 
   engines: "Dark Matter" 
   darkMatterballs: 63 
   shippriceinbeans: 2

Step 3 - Create a template task

tasks:
- name: "Configure space ship config file"
  template:	
    src: /home/student/templates/ship.cfg.j2    # Location of the source template
    dest: -/ship.cfg                            # name of the completed file to be placed on the target system

Step 4 Create a playbook

module-template.yml

- hosts: planet-express

  vars:
     shipname: "Bessie" 
     shiptype: "Intergalactic" 
     engines: "Dark Matter" 
     darkMatterballs: 63 
     shippriceinbeans: 2    

  tasks:
  - name: "Configure space ship config file"
    template:	
      src: /home/student/templates/ship.cfg.j2    # Location of the source template
      dest: -/ship.cfg                            # name of the completed file to be placed on the target system

Step 5 Define the target hosts (aka: The inventory)

[planet-express]
bender    ansible host=10.10.2.3 ansible_ssh_user=bender 
fry       ansible host-10.10.2.4 ansible_ssh_user-fry
zoidberg  ansible host=10.10.2.5 ansible_ssh_user=zoidberg

Step 6 Run the playbook and observe the results

At the end of the video, Zach runs the Ansible playbook and then connects to each machine and shows that the template module has created a ship.cfg file that looks like this:

ship.cfg

[default]
name = Bessie
type = Intergalactic
engine type = Dark Matter
Darkmatter maxcapacity = 63
salesprice = 2
anti matter afterburner = true