Skip to content

Instantly share code, notes, and snippets.

@esoupy
Created August 23, 2012 17:42
Show Gist options
  • Save esoupy/3439301 to your computer and use it in GitHub Desktop.
Save esoupy/3439301 to your computer and use it in GitHub Desktop.
Updated ec2 public key retrieval script. Modified to not append the key if the key already exists.
#!/bin/bash
# Modified to check if the already exists
# processname: ec2-get-ssh
# description: Capture AWS public key credentials for EC2 user
# Source function library
. /etc/rc.d/init.d/functions
# Source networking configuration
[ -r /etc/sysconfig/network ] && . /etc/sysconfig/network
# Replace the following environment variables for your system
export PATH=:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
# Check that networking is configured
if [ "${NETWORKING}" = "no" ]; then
echo "Networking is not configured."
exit 1
fi
start() {
if [ ! -d /root/.ssh ]; then
mkdir -p /root/.ssh
chmod 700 /root/.ssh
fi
# Retrieve public key from metadata server using HTTP
curl -s http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key > /tmp/my-public-key
if [ $? -eq 0 ]; then
echo "EC2: Retrieve public key from metadata server using HTTP."
if [ -s /tmp/my-public-key ]; then
mpk=$(cat /tmp/my-public-key)
if [ -s /root/.ssh/authorized_keys ]; then
echo "checking if key already exists.."
( cat /root/.ssh/authorized_keys | grep "$mpk" ) 2>&1 >> /dev/null && echo "Key already exists." || ( cat /tmp/my-public-key >> /root/.ssh/authorized_keys )
else
cat /tmp/my-public-key >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
fi
rm /tmp/my-public-key
fi
fi
}
stop() {
echo "Nothing to do here"
}
restart() {
stop
start
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
*)
echo $"Usage: $0 {start|stop|restart}"
exit 1
esac
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment