I manage hosting for all sites networked within MetaZaku but the servers themselves are unmanaged; thus, I must manually configure all hosting accounts.

Administrative tasks such as this become tedious. We should automate it using Python.

Configuration File Architecture

Always think like a software architect before starting programming. I must abstract the idea of configuration file templates for general usage.

Assume that we have a folder /etc/sites that contains all configuration files with the extension .conf. Our structure should mirror the following:

$ ls /etc/sites
site1.conf site2.conf site3.conf

There must also be a single template file named template.conf. In a template, the objective is to substitute values for the variables in the template file. We will denote variables by prefixing them with the dollar sign, $.

$ echo "server_name $domain_name" > /etc/sites/template.conf

In this sample template file, we want to replace the variable, $domain_name with the domain name of the website that we will configure in the future.

With this file structure, our program should do the following:

  1. Open the template file for reading and create a new configuration file for writing
  2. Read the template file, line by line
  3. Substitute the variables with the desired value (in this case, the domain name)
  4. Write the substituted line into the new configuration file
  5. Close the files

Time to Program in Python

Create a new file named newconfig.py and edit it with our favourite editor (vi for me):

$ vi /etc/sites/newconfig.py

Afterwards, write the code following the program flow that we described above.

import sys
import io

# Create the new config file for writing
config = io.open(sys.argv[1] + '.conf', 'w')

# Read the lines from the template, substitute the values, and write to the new config file
for line in io.open('template.conf', 'r'):
  line = line.replace('$domain_name', sys.argv[1]) + '\n')

# Close the files

That was easy.

Execution and Usage

Executing a Python file is straightforward at this point but one notable aspect is that the program takes one argument as depicted by sys.argv[1]. That argument is the new domain name. We can execute the script as we execute all other Python scripts:

$ python /etc/sites/newconfig.py website.com

Upon successful execution, a new configuration file named website.com.conf should be made containing the following data: server_name website.com.


This is a very esoteric example for configuration files specifically but the script itself can be modified to process any file template quickly.

Have fun automating your system tasks.