Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script to clean up Ubuntu EC2 instance before packaging as an AMI
#!/bin/bash
# This script cleans up your EC2 instance before baking a new AMI.
# Run the following command in a root shell:
#
# bash <(curl -s https://gist.github.com/justindowning/5921369/raw/ami-clean.sh)
function print_green {
echo -e "\e[32m${1}\e[0m"
}
print_green 'Clean Apt'
apt-get -y autoremove
aptitude clean
aptitude autoclean
print_green 'Remove SSH keys'
[ -f /home/ubuntu/.ssh/authorized_keys ] && rm /home/ubuntu/.ssh/authorized_keys
print_green 'Cleanup log files'
find /var/log -type f | while read f; do echo -ne '' > $f; done
print_green 'Cleanup bash history'
unset HISTFILE
[ -f /root/.bash_history ] && rm /root/.bash_history
[ -f /home/ubuntu/.bash_history ] && rm /home/ubuntu/.bash_history
print_green 'AMI cleanup complete!'
@TropComplique

This comment has been minimized.

Show comment
Hide comment
@TropComplique

TropComplique May 26, 2017

Thanks for sharing.

Thanks for sharing.

@evilpete

This comment has been minimized.

Show comment
Hide comment
@evilpete

evilpete Jun 19, 2018

you really want to also clean up cloud-init cache :

test -d /var/lib/cloud && /bin/rm -rf /var/lib/cloud/*

persistent "rules" in udev
test -f /etc/udev/rules.d/70-persistent-net.rules && /bin/rm /etc/udev/rules.d/70-persistent-net.rules
This effects vmware more then AWS

I'd also suggest replace aptitude clean with apt-get clean since aptitude is not installed by default

also depending on what you have installed check /var/cache/ for crap

( and since your running this as root it is best practice to use full paths for commands )

you really want to also clean up cloud-init cache :

test -d /var/lib/cloud && /bin/rm -rf /var/lib/cloud/*

persistent "rules" in udev
test -f /etc/udev/rules.d/70-persistent-net.rules && /bin/rm /etc/udev/rules.d/70-persistent-net.rules
This effects vmware more then AWS

I'd also suggest replace aptitude clean with apt-get clean since aptitude is not installed by default

also depending on what you have installed check /var/cache/ for crap

( and since your running this as root it is best practice to use full paths for commands )

@mims92

This comment has been minimized.

Show comment
Hide comment
@mims92

mims92 Jul 11, 2018

Also maybe delete generated rsa keys (Debian)

shred -u /etc/ssh/*_key /etc/ssh/*_key.pub

mims92 commented Jul 11, 2018

Also maybe delete generated rsa keys (Debian)

shred -u /etc/ssh/*_key /etc/ssh/*_key.pub

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment