Quick Python code with Jinja2 and config templates
Networking is awesome but some tasks may be quite boring and repetitive. For new campus network installations a lot of time is used just to put a basic initial configuration template on switches.
Each vendor has its proprietary method to distribute configs automagically but sometimes the effort to setup the system is simply too much.
A common practice is to prepare a template in a test environment then copy it changing the IP address, hostname and a few other parameters. That's a manual and error prone procedure.
I took the chance to write a quick Python script to automate the process and generate the config files reading the data from a csv file and a template.
How it works?
The script reads a csv and a template files and uses Jinja2 to create all the single config files.
How to use it?
create a template using the Jinja2 sintax like this:
hostname {{hostname}} inte vlan 1 ip address {{ip}} netmask {{netmask}} username {{username}} password {{password}}
Notice the values between "{{ }}" will be replaced with the values read from the csv file
create a csv file with the values:
lines starting with # are comments
#hostname,ip,netmask,username,password sw1,10.0.0.1,255.255.255.0,admin,sup3rs3cr3t sw2,10.0.0.2,255.255.255.0,admin,sup3rs3cr3t sw3,10.0.0.3,255.255.255.0,admin,sup3rs3cr3t sw4,10.0.0.4,255.255.255.0,admin,sup3rs3cr3t sw5,10.0.0.5,255.255.255.0,admin,sup3rs3cr3t
Run the script. The parameters are: csv file, template file, directory where the config will be stored:
python cfgmaker_jinja2.py list.csv template.txt CGFS
The output
The output of the scritp are 5 files in the CFGS folder with all the values:
hostname sw1
inte vlan 1
ip address 10.0.0.1 netmask 255.255.255.0
username admin password sup3rs3cr3t
hostname sw2
inte vlan 1
ip address 10.0.0.2 netmask 255.255.255.0
username admin password sup3rs3cr3t
hostname sw3
inte vlan 1
ip address 10.0.0.3 netmask 255.255.255.0
username admin password sup3rs3cr3t
hostname sw4
inte vlan 1
ip address 10.0.0.4 netmask 255.255.255.0
username admin password sup3rs3cr3t
hostname sw5
inte vlan 1
ip address 10.0.0.5 netmask 255.255.255.0
username admin password sup3rs3cr3t
Where's the code?
You can find the source code and the example files in BitBucket.