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:
and edit it to:
#!/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.