Skip to content

Instantly share code, notes, and snippets.

@jbfriedrich
Created January 19, 2020 03:36
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jbfriedrich/6521b15871ed6059704e06606148b6c8 to your computer and use it in GitHub Desktop.
Script to "sanitize" a Ubuntu VM to turn it into a template.
#!/bin/bash
# Configure Package Repos
cat <<EOF >/etc/apt/sources.list
deb http://archive.ubuntu.com/ubuntu bionic main restricted universe multiverse
deb-src http://archive.ubuntu.com/ubuntu bionic main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu bionic-updates main restricted universe multiverse
deb-src http://archive.ubuntu.com/ubuntu bionic-updates main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu bionic-backports main restricted universe multiverse
deb-src http://archive.ubuntu.com/ubuntu bionic-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu bionic-security main restricted universe multiverse
deb-src http://security.ubuntu.com/ubuntu bionic-security main restricted universe multiverse
EOF
apt -y update && apt -y dist-upgrade && apt -y autoremove
# Install VMware Tools
apt -y install open-vm-tools
systemctl enable open-vm-tools
# Clean Up Logging
systemctl stop rsyslog
if [ -f /var/log/wtmp ]; then
truncate -s0 /var/log/wtmp
fi
if [ -f /var/log/lastlog ]; then
truncate -s0 /var/log/lastlog
fi
if [ -f /var/log/audit/audit.log ]; then
truncate -s0 /var/log/audit/audit.log
fi
# Clean Up /tmp
rm -rf /tmp/*
rm -rf /var/tmp/*
# Clean Up SSH Keys
rm -rf /etc/ssh/ssh_host_*
cat <<EOF >/etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
# 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
test -f /etc/ssh/ssh_host_dsa_key || dpkg-reconfigure openssh-server
exit 0
EOF
chmod 0755 /etc/rc.local
# Reset Hostname (Prevent cloudconfig from preserving the original hostname)
sed -i 's/preserve_hostname: false/preserve_hostname: true/g' /etc/cloud/cloud.cfg
truncate -s0 /etc/hostname
hostnamectl set-hostname localhost
# Clean Apt Cache
apt clean
# Clean Cloud Init Cache and Logs
cloud-init clean --logs
# Clean Up Shell History
cat /dev/null > ~/.bash_history && history -c
history -w
# Shut Down the VM
shutdown -h now
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment