[PYTHON] How to use Template Engine for Network Engineer

Overview

When I work on a network, I sometimes make a lot of router configurations by changing only the values such as IP address to the same settings.

You can copy and paste each one by hand, but you can easily insert values by using the template engine provided in the programming language.

Here, let's create a router config using a template engine called Jinja2 that is often used in Python.

Please install jinja2 first as a preparation stage.

pip install jinja2

If you have never used pip, please install pip by referring to this article.

The first packages to include in Python setuptools and pip http://www.lifewithpython.com/2012/11/Python-package-setuptools-pip.html

Step 1. Embed one value in one line of config

First, try creating a one-line config (actually a command) called'show bgp summary | inc (AS number)'. If you use Jinja2, you can call it like this.

easy_jinja2.py


#! /usr/bin/env python
# -*- coding: utf-8 -*-

from jinja2 import Template

template = Template( 'show bgp summary | inc {{ asn }}'  )

output_str = template.render( asn='65001' )

print output_str

When executed, the following will be displayed.

%python easy_jinja2.py

show bgp summary | inc 65001

As mentioned above, Jinja2 recognizes the character string enclosed in {{}} as a variable name, and you can embed the actual value using the render function.

By using the template engine in this way, you can easily create a text file with arbitrary values embedded.

Step 2. Embed multiple values in a multi-line config

Next, let's create a config with a few more lines. To embed a value in a string type variable, write it using the Environment class.

easy_jinja2.py


#! /usr/bin/env python
# -*- coding: utf-8 -*-

from jinja2 import Template, Environment

input_str = '''
router bgp 65000
neighbor {{ ip4 }}
shutdown

router bgp 65000
neighbor {{ ip6 }}
shutdown

show bgp summary | inc {{ asn }}
'''

template = Environment().from_string(input_str)

output_str = template.render( ip4='10.1.1.1', ip6='2000::1:1', asn='65001' )

print output_str

When executed, the following will be displayed.

% python easy_jinja2.py

router bgp 65000
neighbor 10.1.1.1
shutdown

router bgp 65000
neighbor 2000::1:1
shutdown

show bgp summary | inc 65001

Step 3. Make a large number of configs with multiple values embedded

Finally, let's create the previous config by embedding values such as multiple IP addresses. However, the usage of the template engine itself is the same as before. Here we use a dictionary type and a for statement to insert values into the template engine.

easy_jinja2.py


#! /usr/bin/env python
# -*- coding: utf-8 -*-

from jinja2 import Template, Environment

input_str = '''
router bgp 65000
neighbor {{ ip4 }}
shutdown

router bgp 65000
neighbor {{ ip6 }}
shutdown
'''
input_str_2 = 'show bgp summary | inc {{  asn }} '

neighbor_info= [
    {
        'ip4' : '10.1.1.1',
        'ip6' : '2000::1:1',
        'asn' : '65001',
    },
    {
        'ip4' : '10.1.1.2',
        'ip6' : '2000::1:2',
        'asn' : '65002',
    },
    {
        'ip4' : '10.1.1.3',
        'ip6' : '2000::1:3',
        'asn' : '65003',
    },
    {
        'ip4' : '10.1.1.4',
        'ip6' : '2000::1:4',
        'asn' : '65004',
    },
    {
        'ip4' : '10.1.1.5',
        'ip6' : '2000::1:5',
        'asn' : '65005',
    },
]

template = Environment().from_string(input_str)

for neighbor in neighbor_info:
    output_str = template.render(  ip4=neighbor['ip4'] , ip6=neighbor['ip6'] )
    print output_str

template = Environment().from_string(input_str_2)

for neighbor in neighbor_info:
    output_str = template.render(  asn=neighbor['asn']  )
    print output_str

The execution result is as follows.

% python easy_jinja2.py

router bgp 65000
neighbor 10.1.1.1
shutdown

router bgp 65000
neighbor 2000::1:1
shutdown

router bgp 65000
neighbor 10.1.1.2
shutdown

router bgp 65000
neighbor 2000::1:2
shutdown

router bgp 65000
neighbor 10.1.1.3
shutdown

router bgp 65000
neighbor 2000::1:3
shutdown

router bgp 65000
neighbor 10.1.1.4
shutdown

router bgp 65000
neighbor 2000::1:4
shutdown

router bgp 65000
neighbor 10.1.1.5
shutdown

router bgp 65000
neighbor 2000::1:5
shutdown
show bgp summary | inc 65001
show bgp summary | inc 65002
show bgp summary | inc 65003
show bgp summary | inc 65004
show bgp summary | inc 65005

As mentioned above, you can easily create a similar config while changing the value by using the template engine.

Finally

When a task with many repetitions like this stands in front of me, I often get confused as to whether it is faster to copy and paste by hand or to create a tool and devise it.

When I try to create a tool with a heavy waist, I often say, "I was able to do it in a surprisingly short time!" When I actually wrote this tool, I could only write it on the train that happened to sit. It was just 30 minutes. Once created, it can often be reused for other tasks, and there are situations where it can be used anywhere, not just for config creation.

If you make a mistake in an unexpected place when you are manually creating the router config, or if you have a small trouble such as "I got it, there was an extra character in every one!" You need to fix it one by one repeatedly, but if you are using the template engine, you only need to fix one place to complete the correction! In many cases, the work itself can be simplified.

If you have a job to make a lot of router configs that are going to break your heart, please try the template engine once.

Recommended Posts

How to use Template Engine for Network Engineer
How to use template engine in pyramid 1 file application
Use Jinja2 for PasteScript template engine
How to use cybozu.com developer network (Part 2)
[Python] Organizing how to use for statements
How to use Pylint for PyQt5 apps
How to use "deque" for Python data
How to use fingerprint authentication for KDE
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use MkDocs for the first time
How to use image-match
How to use shogun
How to use Pandas 2
How to use Virtualenv
How to use numpy.vectorize
How to use pytest_report_header
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to use data analysis tools for beginners
How to use IPython
How to use virtualenv
How to use Matplotlib
How to use iptables
How to use numpy
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv
How to use list []
How to use python-kabusapi
How to use OptParse
How to use return
How to use dotenv
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
[BigQuery] How to use BigQuery API for Python -Table creation-
[For beginners] How to use say command in python!
How to use Django on Google App Engine / Python
How to use Qt Designer
How to use search sorted
[gensim] How to use Doc2Vec
python3: How to use bottle (2)
Understand how to use django-filter
How to use the generator
[Python] How to use list 1
How to use FastAPI ③ OpenAPI
How to use Python argparse
How to use IPython Notebook
How to use Pandas Rolling
[Note] How to use virtualenv
How to use redis-py Dictionaries
Python: How to use pydub
[Python] How to use checkio