import os
import re
import csv
import string
class ConfigBuilder(object):
def __init__(self, CSV,basetemplatefile,vrftemplatefile):
self.CSV = CSV
self.basetemplatefile = basetemplatefile
self.basetemplatecontents = ''
with open(self.basetemplatefile) as b:
self.basetemplatecontents = b.read()
self.vrftemplatefile = vrftemplatefile
self.vrftemplatecontents = ''
self.baseresultstring = self.basetemplatecontents
with open(self.vrftemplatefile) as v:
self.vrftemplatecontents = v.read()
self.vrfresultstring = ''
def generateBaseConfig(self):
# OPEN CSV CONFIG FILE AND READ INTO AN ARRAY
with open(self.CSV, mode='r') as csvfile:
Detail_file = csv.reader(csvfile, delimiter=',')
# Cycle through Each ITEM-VALUE pair in the DETAIL FILE
for row in Detail_file:
# DEREFERENCE row ARRAY FOR CLARITY IN READING CODE
ITEM = row[0]
VALUE = row[1]
# CHECK TO MAKE SURE THE CONFIG_VALUE ISN"T BLANK
if VALUE.strip()!='':
# DO THE ACTUAL SUBSTITUTION
self.baseresultstring = self.baseresultstring.replace(ITEM,VALUE)
return self.baseresultstring
def generateAgencyVRFs(self):
NumVRFs = self.queryitem('@NUMBER_OF_AGENCY_VRFS')
for x in range(0, int(NumVRFs)):
print x
# OPEN CSV CONFIG FILE AND READ INTO AN ARRAY
self.vrfresultstring = self.vrfresultstring + self.vrftemplatecontents
with open(self.CSV, mode='r') as csvfile:
Detail_file = csv.reader(csvfile, delimiter=',')
# Cycle through Each ITEM-VALUE pair in the DETAIL FILE
for row in Detail_file:
# DEREFERENCE row ARRAY FOR CLARITY IN READING CODE
ITEM = row[0]
VALUE = row[1]
# remove VRF1, VRF2, etc in ITEM key and replace with just VRF so I can use one template for all vrfs
ITEM = ITEM.replace(re.match('VRF[0-9]',ITEM), 'VRF')
print ITEM + '=' + VALUE
# CHECK TO MAKE SURE THE CONFIG_VALUE ISN"T BLANK
if VALUE.strip()!='':
# DO THE ACTUAL SUBSTITUTION
self.vrfresultstring = self.vrfresultstring.replace(ITEM,VALUE)
return self.vrfresultstring
def queryitem(self,querystring):
# OPEN CSV CONFIG FILE AND READ INTO AN ARRAY
with open(self.CSV, mode='r') as csvfile:
Detail_file = csv.reader(csvfile, delimiter=',')
# Cycle through Each ITEM-VALUE pair in the DETAIL FILE
for row in Detail_file:
# DEREFERENCE row ARRAY FOR CLARITY IN READING CODE
ITEM = row[0]
VALUE = row[1]
if VALUE.strip()!='':
if ITEM == querystring:
queryresult = VALUE
return queryresult
def writeconfig(self,outputfilename,FinalOutput):
if os.path.isfile(outputfilename):
os.remove(outputfilename)
with open(outputfilename + '.txt', 'w') as outputFile:
print '\n WRITING FINAL CONFIG FILE: ' + outputfilename + '.txt'
outputFile.write(FinalOutput)
def fullbuild(self):
baseconfig = self.generateBaseConfig()
vrfconfig = self.generateAgencyVRFs()
outputfilename = self.queryitem('@RTR_NAME_OF_ROUTER')
FinalOutput = baseconfig + vrfconfig
self.writeconfig(outputfilename,FinalOutput)
def main():
MPLSGen = ConfigBuilder('RouterDetails.csv','BaseMPLSRouter.tmpl','AgencyVRF.tmpl')
MPLSGen.fullbuild()
if __name__ == '__main__':
main()