Templates
Let's learn what templates are and how to create them using Jinja2.
We'll cover the following
What is a template?
Ansible uses Jinja2 templates to enable dynamic expressions and access variables in the group_vars
and host_vars
data dictionaries. All templates are compiled on the local Linux host at runtime, and then
deployed to the target host. This is done to minimize the amount of information passed to the target device, allowing only what is required to execute the playbook.
Create templates
The next step is to build dynamic templates. Now that a data dictionary comprising key-value pairs along with structured lists exists, templates can be created. The Jinja2 templates substitute portions of configuration commands with dynamic data from the dictionary for a device or group of devices.
Exact Cisco configuration commands, including syntax, nesting, and spacing, are required to develop idempotent configurations. If the spacing is off, the playbook will still execute and make the changes. However, during check mode or future executions of the playbook, the incorrectly spaced lines of configuration will always show up as a change, even if the commands are already present on the device.
Static/explicit statements
With network device configurations, there are a lot of static configuration commands without any real
valuable information that can be abstracted into a data model. Often, it is desired to explicitly execute
commands and not require any dynamic data from the dictionary. Many global configurations follow this
pattern. Consider the 01_ios_global.j2
template, which covers
all devices, regardless of platform, and the global configuration commands we will explicitly run on each
device:
Get hands-on with 1400+ tech skills courses.