Generalizing Debian 12 Machine for VM Template
Overview
This document outlines generalizing a Debian 12 VM for preperation to make it a VM Template
Update packages
sudo apt update
sudo apt upgrade -y
sudo apt install qemu-guest-agent -y
sudo systemctl enable qemu-guest-agent --nowRemove Unique Data
# stop services for cleanup
sudo service rsyslog stop
# clear audit logs
if [ -f /var/log/wtmp ]; then
truncate -s0 /var/log/wtmp
fi
if [ -f /var/log/lastlog ]; then
truncate -s0 /var/log/lastlog
fi
# cleanup /tmp directories
sudo rm -rf /tmp/*
sudo rm -rf /var/tmp/*
# cleanup current ssh keys
sudo rm -f /etc/ssh/ssh_host_*
# add check for ssh keys on reboot...regenerate if necessary
cat << 'EOL' | sudo tee /etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# dynamically create hostname (optional)
#if hostname | grep localhost; then
# hostnamectl set-hostname "$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 13 ; echo '')"
#fi
#
# check for SSH keys and create if not present
test -f /etc/ssh/ssh_host_dsa_key || dpkg-reconfigure openssh-server
exit 0
EOL
# make sure the script is executable
sudo chmod +x /etc/rc.local
# reset hostname
# prevent cloud-init from preserving the original hostname
sed -i 's/preserve_hostname: false/preserve_hostname: true/g' /etc/cloud/cloud.cfg
sudo truncate -s0 /etc/hostname
sudo hostnamectl set-hostname localhost
# cleanup apt
sudo apt clean
# set DHCP to use mac - keying off of a default line is a little bit of a hack to insert the replacement text, but we need the replaced text inserted under the active nic settings
# also look in /etc/netplan for other config files
sudo sed -i 's/optional: true/dhcp-identifier: mac/g' /etc/netplan/50-cloud-init.yaml
# cleans out all of the cloud-init cache/logs - this is mainly cleaning out networking info
sudo cloud-init clean --logs
# disable swap
sudo swapoff --all
sudo sed -ri '/\sswap\s/s/^#?/#/' /etc/fstab
# cleanup shell history
cat /dev/null > ~/.bash_history && history -c
history -w
# shutdown
shutdown -h now