Python Jinja2 Template: YAML File Cisco Example Tutorial

Python Jinja2 template example with YAML

Python Jinja2 template
Python Jinja2 templates are an essential tool for a network operator. A key benefit to network automation using configuration templates is consistency. The ability to predictably make changes across a large number of network devices is key to maintaining and troubleshooting infrastructures.

Python Jinja2 templates are similar to text templates in Go. Depending on your circumstance, one method may make sense over another. This example assumes your using Mac or Linux.


Initialize virtual environment

virtualenv venv
cd venv
source ./bin/active

Install dependencies

for dep in pyyaml jinja2 markupsafe;do ./bin/easy_install $dep;done

Create template

Lets create the Jinja2 template. Notice the for loop which allows us to iterate over a sequence, in this case, ‘vlan’. We’ll use a curly brace and a percent symbol. Also, we’re using whitespace control with the minus sign. By adding a minus sign  the whitespace after that block (or before if you choose) will be removed.

Create YAML file

While YAML is used as a data source to populate this template, CSV is another easy to work with source. This Python Jinja2 tutorial is using YAML to read from a file.

Create Python script

This small Python script will pull together your YAML data file and Jinja2 cli configuration template. This script enables network automation and programmability because you don’t need to do it manually.

Run Python script

Running the python script will generate the Cisco configuration file. No need to copy and paste. This eliminates human error.


See also:
Cisco ACI ELAM Packet Capture
Cisco ACI Automation with cURL
Cisco ACI Python Cobra Examples
Cisco ACI Troubleshooting with Moquery
Cisco ACI Troubleshooting with icURL
Run Python Script from Windows Task Scheduler