Python script to replace templates in configuration files in VMs

The idea behind this script is you create a template VM, and when you need a new VM, you duplicate the disk image and use the script to put final values into configuration files. This script will take a disk image containing a configuration file like:

HOSTNAME=@HOSTNAME@

and edit it to:

HOSTNAME=yourhost.example.com

#!/usr/bin/python

image = "disk.img"
root_filesystem = "/dev/vg_template/lv_root"
filename = "/etc/sysconfig/network"
pattern = "@HOSTNAME@"
replacement = "yourhost.example.com"

import tempfile
import os
import fileinput
import shutil
import guestfs

g = guestfs.GuestFS ()

g.add_drive (image)
g.launch ()
g.mount_options ("", root_filesystem, "/")

tmpdir = tempfile.mkdtemp ()
tmpfile = os.path.join (tmpdir, "file")

g.download (filename, tmpfile)

for line in fileinput.FileInput (tmpfile, inplace=1):
    line = line.replace (pattern, replacement)
    print line,

g.upload (tmpfile, filename)

g.umount_all ()
g.sync ()

shutil.rmtree (tmpdir)

If you have to make many changes to a VM image, don’t run this script repeatedly. Instead, duplicate the download ... upload section of the code as required.

2 Comments

Filed under Uncategorized

2 responses to “Python script to replace templates in configuration files in VMs

  1. foo

    Surely folks who want this would just use puppet?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s