Templates

For as long as I can remember, working as a network engineer, I have always used a kind of network template. In my experience, many of the network devices have sections of the network configuration that are identical, especially if these devices serve the same role in the network.

Most of the time, when we need to provision a new device, we use the same configuration in the form of a template, replace the necessary fields, and copy the file over to the new device. With Ansible, you can automate all of the work by using the template module (http://docs.ansible.com/ansible/template_module.html).

The base template file we are using utilizes the Jinja2 template language (http://jinja.pocoo.org/docs/). We briefly discussed the Jinja2 templating language in Chapter 7, The Python Automation Framework – Ansible Basics, and we will look at it a bit more here. Just like Ansible, Jinja2 has its own syntax and method of doing loops and conditionals; fortunately, we just need to know the very basics of it for our purpose. The Ansible template is an important tool that we will be using in our daily task, and we will spend more of this section exploring it. We will learn the syntax by gradually building up our playbook from simple to more complex.

The basic syntax for template usage is very simple; you just need to specify the source file and the destination location that you want to copy it to.

We will create an empty file for now:

$ touch file1

Then, we will use the following playbook to copy file1 to file2. Note that the playbook is executed on the control machine only. Next, we will specify the path of both the source and destination files as arguments for the template module:

---
- name: Template Basic
hosts: localhost

tasks:
- name: copy one file to another
template:
src=./file1
dest=./file2

We do not need to specify a host file during playbook execution since the localhost is available by default. However, you will get a warning:

$ ansible-playbook chapter8_7.yml
[WARNING]: provided hosts list is empty, only localhost is available
<skip>
TASK [copy one file to another] ************************************************

changed: [localhost]
<skip>

The source file can have any extension, but since they are processed through the Jinja2 template engine, let's create a text file called nxos.j2 as the template source. The template will follow the Jinja2 convention of using double curly brace to specify the variables:

    hostname {{ item.value.hostname }}
feature telnet
feature ospf
feature bgp
feature interface-vlan

username {{ item.value.username }} password {{ item.value.password
}} role network-operator
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset