Preparing Ubuntu template virtual machines

Bob Plankers has a great post over at for preparing CentOS based virtual machines for being a template. As I’ve started working with Ubuntu more I decided to take that list and Ubuntu-ize it (mostly from proding by Sarah Zelechoski - one of the smartest people I’ve ever had the privilege to work with…so many thank you’s). Anyways here is that guide… Ubuntu-ized.

Stop logging services (auditd and rsyslog):

service auditd stop
service rsyslog stop

Check for, and remove old kernels

Check your current kernel by running

uname -r

Then run

dpkg -l | grep linux-image-

If additional images are listed, remove them by running

apt-get autoremove linux-image-#.##.#

You can remove multiple images all on the same line just by listing them one after another.

Clean out apt-get

apt-get clean

Force the logs to rotate & remove old logs we don’t need

logrotate –f /etc/logrotate.conf
find /var/log -name "*.gz" -type f -delete

Truncate the audit logs (and other logs we want to keep placeholders for)

cat /dev/null > /var/log/audit/audit.log
cat /dev/null > /var/log/wtmp
cat /dev/null > /var/log/lastlog

Remove the udev persistent device rules

Well, saved a step here - there are rules which exclude creating files that match MAC addresses for VMware, Hyper-V, KVM, Xen, and virtualbox (see /lib/udev/rules.d/75-persistent-net-generator.rules). So long as your MAC matches this, nothing to clean up. Otherwise

rm -f /etc/udev/rules.d/70-persistent-net.rules

It will be recreated on the next boot, so any time you power on this VM (updates maybe?) you’ll need to delete this file again so it is not saved in the template.

Remove the traces of the template MAC address and UUIDs.

Here is another step you shouldn’t need to do, however you may want to check /etc/network/interfaces to verify

Clean /tmp out

rm -rf /tmp/*
rm -rf /var/tmp/*

Remove the SSH host keys

rm –rf /etc/ssh/*key*
rm –rf ~/.ssh/authorized_keys

Update network config

If you have set /etc/network/interfaces, make sure to reset for cloning purposes. For example as I wrote this it had a static IP address which I changed to DHCP before shutting down and converting to a template.

Remove hostname

If you have named your virtual machine anything other than localhost, and want the template to spin up with a generic name, versus say “ubuntu-template” remove entry from /etc/hostname

cat /dev/null > /etc/hostname

Remove the user’s shell history

If you have switched to root at any point, do this as root and individual user accounts

history -w
history -c

That should about do it, depending on where this template is going, make sure any ISOs attached to the CD-ROM or networks for the NIC’s are adjusted properly. While many of the steps were the same there were a few differences to be aware of. Anything else you like to clean out? Comment below please!