Skip to content

Instantly share code, notes, and snippets.

@weavenet
Created January 6, 2012 20:58
Show Gist options
  • Save weavenet/1572374 to your computer and use it in GitHub Desktop.
Save weavenet/1572374 to your computer and use it in GitHub Desktop.
Custom rc.local for RHEL5 to create ec2-user, enable full sudo and execute user-data on first boot
#!/bin/sh
#
# Modified by bweaver to add root key to ea user
#
# 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
USER=ec2-user
GROUP=$USER
HOME=/home/$USER
ATTEMPTS=5
FAILED=0
grep ^$GROUP: /etc/group > /dev/null
if [ $? -ne 0 ]; then
groupadd $GROUP
if [ $? -ne 0 ]; then
echo "Error adding group $GROUP"
exit 1
fi
fi
grep ^$USER: /etc/passwd > /dev/null
if [ $? -ne 0 ]; then
useradd -d $HOME -g $GROUP -G root $USER
if [ $? -ne 0 ]; then
echo "Error adding user: $USER"
exit 1
fi
fi
chage -I -1 -m 0 -M 99999 -E -1 $USER
if [ ! -d $HOME/.ssh ] ; then
mkdir -p $HOME/.ssh
chmod 0700 $HOME/.ssh
restorecon $HOME/.ssh
fi
# Fetch public key using HTTP
while [ ! -f $HOME/.ssh/authorized_keys ]; do
curl -f http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key > /tmp/aws-key 2>/dev/null
if [ $? -eq 0 ]; then
cat /tmp/aws-key >> $HOME/.ssh/authorized_keys
chmod 0600 $HOME/.ssh/authorized_keys
restorecon $HOME/.ssh/authorized_keys
chown -R $USER:$GROUP $HOME
rm -f /tmp/aws-key
echo "Successfully retrieved AWS public key from instance metadata"
else
FAILED=$(($FAILED + 1))
if [ $FAILED -ge $ATTEMPTS ]; then
echo "Failed to retrieve AWS public key after $FAILED attempts, quitting"
break
fi
echo "Could not retrieve AWS public key (attempt #$FAILED/$ATTEMPTS), retrying in 5 seconds..."
sleep 5
fi
done
# Execute user-data as shell script
curl -s http://169.254.169.254/1.0/user-data| bash
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment