I recently wrote a truly generic template builder/multi-replace tool in Python that I would like to share

I recently wrote a generic template builder/multi-replace tool that I though you guys might find useful if you have any cookie cutter deployments you do. It’s a HUGE timesaver when building multiple devices that are similar.

When I say multi-replace I mean it will replace the original value every time it sees it, even if it occurs multiple times, and it will replace multiple old value/new value pairs in one run.

Summary of program:
• You can take any text file and use it as a template.
• The values to be replace are populated in a 2 column CSV file, where column 1 matches your placeholder in the template, and column 2 is the new value to be inserted.
• The program reads in template, replaces values in the template in memory, and writes the updated content to an output file.
• It’s basic Python, so it’s cross-platform
• No extra Python modules are needed
• It’s written so that it can be included in other Python programs as an import – at least I think. I haven’t actually tested that.

Use Cases:
• Create repeatable, consistent, cookie-cutter device deployments to aid in standardization
• Swap old IPs to new IPs in config when Re-IPing NATs in a firewall (here you wouldn’t create variables, just use old IP as the variable, and new IP as the new value)
• Wherever you need to do a multi-replace and don’t want to do it one by one over and over.

Instructions:
1. Edit your template and put placeholders in it (or not if you’re swapping values instead of building templates).
2. Add those placeholders to the CSV file to match on in the first column
a. I use the form of @variablename just to make the variables easy to find in the template when you’re editing the template, but it doesn’t really matter what your variables are called, as long as they match in the first column of the CSV
3. Put a new value in column 2 of the CSV

This doesn’t have to be rewritten every time you change your template – it doesn’t care as long as it has something to match on.

Here is a link to view the color coded source code.
http://nerdingout.net/pastetool/view/85fdf864

Here is a direct download link for the script (you’ll probably want to rename it, this gives you a random filename.py)
http://nerdingout.net/pastetool/view/download/85fdf864

You’ll need Python 2.7 installed – no special packages needed.

Usage is as follows:

C:\dev\templatebuilder>python TemplateBuilder.py –help
usage: TemplateBuilder.py [-h] InputFile TemplateFile OutputFile

build a config from template

positional arguments:
InputFile The CSV input file
TemplateFile The Template
OutputFile The Output File

optional arguments:
-h, –help show this help message and exit



One Comment

Comments are closed.