Template network config generation with Python and Jinja2

What is this?

A Python script that generates a Cisco config *. A sample that fills parameters using Jinja2. It seems to be very versatile, so make a note for yourself. If you prepare two config templates including variables and CSV that summarizes the values for variables and execute the script, multiple configs will be output as files.

What is Jinja2?

Template engine for Python. For more information, see Honke.

Origin of Jinja2 Naming

The name Jinja was chosen because it’s the name of a Japanese temple and temple and template share a similar pronunciation. It is not named after the city in Uganda.

Japanese temples (shrines) have similar pronunciations to templates. (There is a city called Jinja in Uganda, but that's not it)

0. Preparation

Make Jinja2 available with pip. Prepare three files and one directory (each explained below).

~ $pip3 list | grep Jinja2
Jinja2 (2.8)
~ $ls
build_templates.py	config_template.txt	configs			inventory.csv
~ $

SS 2017-06-06 17.37.04.png

  1. configs ... Directory where multiple config files are generated. The contents are empty.
  2. inventory.csv ... config template variable file.
  3. config_template.txt ... config template file.
  4. build_templates.py ... main script.

1. configs directory

It's empty.

~ $ls ./configs
~ $
  1. inventory.csv You can create it in Excel, or you can manage variables with a script.
~ $cat inventory.csv 
hostName,serialNumber,platformId,site,ipAddress,subnet,username,password,enablepass
Cat01,12345678901,WS-C2960X-48FPD-L,Tokyo,10.10.10.101,255.255.255.0,cisco,C1sco12345,C1$co
Cat02,22345678901,WS-C2960X-48FPD-L,Osaka,10.10.10.102,255.255.255.0,cisco,C1sco12345,C1$co
Cat03,32345678901,WS-C2960X-48FPD-L,Nagoya,10.10.10.103,255.255.255.0,cisco,C1sco12345,C1$co

SS 2017-06-06 17.38.16.png

  1. config_template.txt The config is familiar to network engineers, but the parameter you want to complement dynamically is {{variable}}. Since Jinja2 is also used in Ansible, there may be many people who do not feel uncomfortable.
~ $cat config_template.txt 
hostname {{hostName}}
!
enable password {{enablepass}}
!
username {{username}} password 0 {{password}}
no aaa new-model
!
int vlan 1
ip address {{ipAddress}} {{subnet}}
!
end

As already referenced in the variables section, Ansible uses Jinja2 templating to enable dynamic expressions and access to variables.

  1. build_templates.py build_templates is a sample function that inputs a config template (config_template.txt) and a variable CSV (inventory.csv) and outputs multiple config files.

build_templates.py


# -*- coding: utf-8 -*-
import jinja2
import csv

CONFIGS_DIR= "./configs/"
DEVICES="./inventory.csv"
TEMPLATE="./config_template.txt"

def build_templates(template_file, devices):

    templateLoader = jinja2.FileSystemLoader('./')
    templateEnv = jinja2.Environment(loader=templateLoader)
    template = templateEnv.get_template(template_file)

    f = open(devices, 'rt')
    try:
        reader = csv.DictReader(f)
        for dict_row in reader:
            outputText = template.render(dict_row)

            config_filename = CONFIGS_DIR + dict_row['hostName'] + '-' + dict_row['site'] + '-config'
            with open(config_filename, 'w') as config_file:
                config_file.write(outputText)
            print("Config generation: %s" % config_filename)

    finally:
        f.close()

if __name__ == "__main__":
    build_templates(TEMPLATE, DEVICES)

point

--Read line by line (device by device) from CSV file with Python dictionary (csv.DictReader) --Variable completion (template.render (dict_row)) to template and output --Loop as many as the number of devices (for dict_row in reader) ――The way to write Jinja2 is written separately, but it seems that you can write even one as follows.

Quote


import os
import jinja2


def render(tpl_path, context):
    path, filename = os.path.split(tpl_path)
    return jinja2.Environment(
        loader=jinja2.FileSystemLoader(path or './')
    ).get_template(filename).render(context)

5. Run

~ $python3 build_templates.py 
Config generation: ./configs/Cat01-Tokyo-config
Config generation: ./configs/Cat02-Osaka-config
Config generation: ./configs/Cat03-Nagoya-config
~ $
~ $ls ./configs/
Cat01-Tokyo-config	Cat02-Osaka-config	Cat03-Nagoya-config
~ $
~ $cat ./configs/Cat01-Tokyo-config 
hostname Cat01
!
enable password C1$co
!
username cisco password 0 C1sco12345
no aaa new-model
!
int vlan 1
ip address 10.10.10.101 255.255.255.0
!
end
~ $
~ $
~ $cat ./configs/Cat02-Osaka-config 
hostname Cat02
!
enable password C1$co
!
username cisco password 0 C1sco12345
no aaa new-model
!
int vlan 1
ip address 10.10.10.102 255.255.255.0
!
end
~ $
~ $

SS 2017-06-06 19.20.03.png

it is a good feeling. It seems that it can be used for other purposes.

reference

Usage of csv.DictReader ... Easy-to-understand explanation of CSV parsing CiscoDevNet / apic-em-samples-aradford ... It's messy, but it contains a lot.

Recommended Posts

Template network config generation with Python and Jinja2
Neural network with OpenCV 3 and Python 3
Jinja2 | Python template engine
Programming with Python and Tkinter
Encryption and decryption with Python
Python and hardware-Using RS232C with Python-
Neural network with Python (scikit-learn)
Network programming with Python Scapy
Works with Python and R
Web application with Python3.3.1 + Bottle (1) --Change template engine to jinja2
Easily build network infrastructure and EC2 with AWS CDK Python
Communicate with FX-5204PS with Python and PyUSB
Shining life with Python and OpenCV
Install Python 2.7.9 and Python 3.4.x with pip.
AM modulation and demodulation with python
[Python] font family and font with matplotlib
Scraping with Node, Ruby and Python
Measuring network one-way delay with python
Scraping with Python and Beautiful Soup
JSON encoding and decoding with python
Hadoop introduction and MapReduce with Python
[GUI with Python] PyQt5-Drag and drop-
Reading and writing NetCDF with Python
I played with PyQt5 and Python3
Password generation in texto with python
Reading and writing CSV with Python
CSRF countermeasure token generation with Python
Multiple integrals with Python and Sympy
Coexistence of Python2 and 3 with CircleCI (1.0)
Easy modeling with Blender and Python
Sugoroku game and addition game with python
FM modulation and demodulation with Python
Gradation image generation with Python [1] | np.linspace
Communicate between Elixir and Python with gRPC
Data pipeline construction with Python and Luigi
Calculate and display standard weight with python
Monitor Mojo outages with Python and Skype
FM modulation and demodulation with Python Part 3
[Automation] Manipulate mouse and keyboard with Python
Passwordless authentication with RDS and IAM (Python)
Python installation and package management with pip
Using Python and MeCab with Azure Databricks
POST variously with Python and receive with Flask
Capturing images with Pupil, python and OpenCV
Fractal to make and play with Python
A memo with Python2.7 and Python3 on CentOS
Multilingualize webapp2 applications with pybabel and Jinja2
Use PIL and Pillow with Cygwin Python
Create and decrypt Caesar cipher with python
3. Natural language processing with Python 2-1. Co-occurrence network
CentOS 6.4 with Python 2.7.3 with Apache with mod_wsgi and Django
Reading and writing JSON files with Python
Dealing with "years and months" in Python
Tweet analysis with Python, Mecab and CaboCha
Linking python and JavaScript with jupyter notebook
Traffic monitoring with Kibana, ElasticSearch and Python
Encrypt with Ruby (Rails) and decrypt with Python
Easily download mp3 / mp4 with python and youtube-dl!
Operate home appliances with Python and IRKit
Practice web scraping with Python and Selenium
Easy web scraping with Python and Ruby