Skip to content

Instantly share code, notes, and snippets.

@moismailzai
Forked from jdowning/vagrant-clean.sh
Last active September 3, 2018 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moismailzai/0864e90d55d508ec8f5aa1ccd68887c6 to your computer and use it in GitHub Desktop.
Save moismailzai/0864e90d55d508ec8f5aa1ccd68887c6 to your computer and use it in GitHub Desktop.
Script to clean up Ubuntu Vagrant box before packaging
#!/bin/bash
# This script zeroes out any space not needed for packaging a new Ubuntu Vagrant base box.
# Run the following command in a root shell:
#
# bash <(curl -s https://gist.githubusercontent.com/moismailzai/0864e90d55d508ec8f5aa1ccd68887c6/raw/fdfd7b28bd00623311689a50754307b06e2e5922/vagrant-clean.sh)
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
function print_green {
echo -e "\e[32m${1}\e[0m"
}
print_green 'Clean Apt'
apt-get -y autoremove
aptitude clean
aptitude autoclean
print_green 'Cleanup bash history'
unset HISTFILE
[ -f /root/.bash_history ] && rm /root/.bash_history
[ -f /home/vagrant/.bash_history ] && rm /home/vagrant/.bash_history
print_green 'Cleanup log files'
find /var/log -type f | while read f; do echo -ne '' > $f; done
print_green 'Cleanup cache files'
for i in /home/vagrant/.viminfo /home/root/.viminfo /home/vagrant/.vim/undodir/*; do
[[ -f $i ]] || continue
rm -fr "$i"
echo removed $i
done
print_green 'Whiteout root'
count=`df --sync -kP / | tail -n1 | awk -F ' ' '{print $4}'`
let count--
dd if=/dev/zero of=/tmp/whitespace bs=1024 count=$count
rm /tmp/whitespace
print_green 'Whiteout /boot'
count=`df --sync -kP /boot | tail -n1 | awk -F ' ' '{print $4}'`
let count--
dd if=/dev/zero of=/boot/whitespace bs=1024 count=$count;
rm /boot/whitespace
print_green 'Whiteout swap'
for swappart in $(grep partition /proc/swaps | awk -F ' ' '{print $1}')
do
swapoff $swappart
dd if=/dev/zero of=$swappart
mkswap -f $swappart
swapon $swappart
done
print_green 'Zero out disk'
dd if=/dev/zero of=/EMPTY bs=1M 2>/dev/null
rm -f /EMPTY
print_green 'Vagrant cleanup complete!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment