Skip to content

Instantly share code, notes, and snippets.

@garthk
Last active August 29, 2015 14:27
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 garthk/d51b17bdab34ba4d3522 to your computer and use it in GitHub Desktop.
Save garthk/d51b17bdab34ba4d3522 to your computer and use it in GitHub Desktop.
CentOS cleanup prior to taking AMI

A CentOS image straight off the marketplace shelf boots with the instance key loaded into authorized_keys for root. We prefer ec2-user. This new /etc/rc.d/rc.local helps, along with the pre-image procedure in ready.sh.

#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local
function get_home() {
getent passwd $1 | cut -f 6 -d :
}
function set_random_password_on_first_boot() {
set -x # TODO: remove
USER=$1
SENTINEL=`get_home $USER`/firstrun
if [ -f $SENTINEL ]; then
dd if=/dev/urandom count=50|md5sum|passwd --stdin root
passwd -l root
rm $SENTINEL
fi
}
function ssh_authorize() {
set -x # TODO: remove
USER=$1
SSHDIR=`get_home $USER`/.ssh
AUTHORIZED=$SSHDIR/authorized_keys
if [ ! -d $SSHDIR ]; then
mkdir -m 0700 -p $SSHDIR
restorecon $SSHDIR
fi
ReTry=0
while [ ! -f $SSHDIR/authorized_keys ] && [ $ReTry -lt 10 ]; do
sleep 2
curl -f http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key > $AUTHORIZED.new
if [ 0 -eq 0 ]; then
mv $AUTHORIZED.new $AUTHORIZED
fi
ReTry=$[Retry+1]
done
chown -R $USER $SSHDIR
chmod 600 $AUTHORIZED && restorecon $SSHDIR/authorized_keys
}
set_random_password_on_first_boot root
set_random_password_on_first_boot ec2-user
ssh_authorize ec2-user
# paste these in raw, or source
groupadd -g 500 ec2-user
useradd -g ec2-user ec2-user
cat > /etc/sudoers.d/ec2-user <<EOF
ec2-user ALL = NOPASSWD: ALL
ec2-user ALL=(ALL) NOPASSWD:ALL
EOF
export HISTFILESIZE=0
export HISTSIZE=0
unset HISTFILE
history -c
find /root /home -name .bash_history | xargs --no-run-if-empty rm
rm -rf /etc/ssh/*key*
rm -rf /home/ec2-user/.ssh
rm -rf /root/.ssh
find /var/log -type f -delete
touch /root/firstrun
touch /home/ec2-user/firstrun
halt -p
@garthk
Copy link
Author

garthk commented Aug 17, 2015

Nope. Not working. Bad. FIXED.

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