Skip to content

Instantly share code, notes, and snippets.

@maurorappa
Last active October 13, 2017 10:09
Show Gist options
  • Save maurorappa/b97da3a2facfc230f046f35bbe86f0fa to your computer and use it in GitHub Desktop.
Save maurorappa/b97da3a2facfc230f046f35bbe86f0fa to your computer and use it in GitHub Desktop.
VM disk cleanup script to minize its size
###
# Script which helps to minimize the final image size
###
# Set default value of the input variables
CI_STEP=${CI_STEP:-null}
EXPORT_TYPE=${EXPORT_TYPE:-null}
# Use sudo if not root
CMD="bash"
if [ $UID != 0 ]; then
CMD="sudo -s"
fi
$CMD -- <<END
if [ $CI_STEP == "soe" ]; then
# Required for the next CI steps where we can not type the sudo password
echo "==> Create sudoers file for the cfgmgmt user"
echo "cfgmgmt ALL=(ALL:ALL) NOPASSWD: ALL" > /etc/sudoers.d/cfgmgmt
fi
echo "==> Clean up yum cache of metadata and packages to save space"
yum -y --enablerepo='*' clean all
echo "==> Clear core files"
rm -f /core*
echo "==> Removing temporary files used to build box"
rm -rf /tmp/*
echo "==> Rebuild RPM DB"
rpmdb --rebuilddb
rm -f /var/lib/rpm/__db*
echo "==> Remove mac address from eth0 configuration"
sed -i -r '/^(HWADDR|UUID)/d' /etc/sysconfig/network-scripts/ifcfg-eth0
echo "==> Remove net udev rules"
rm -f /etc/udev/rules.d/70-persistent-net.rules
echo "==> Clear out swap and disable until reboot"
set +e
swapuuid=$($SUDO /sbin/blkid -o value -l -s UUID -t TYPE=swap);
case "$?" in
2|0) ;;
*) exit 1 ;;
esac
set -e
if [ "x${swapuuid}" != "x" ]; then
# Whiteout the swap partition to reduce box size
# Swap is disabled till reboot
swappart="`readlink -f /dev/disk/by-uuid/$swapuuid`"
/sbin/swapoff "$swappart"
dd if=/dev/zero of="$swappart" bs=1M || echo "dd exit code $? is suppressed"
/sbin/mkswap -U "$swapuuid" "$swappart"
fi
echo "==> Zeroing out empty area to save space in the final image"
dd if=/dev/zero of=/EMPTY bs=1M || echo "dd exit code $? is suppressed"
rm -f /EMPTY
echo "==> Syncing disks"
sync
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment