Created
July 31, 2008 18:19
-
-
Save codeslinger/3494 to your computer and use it in GitHub Desktop.
Robust script to retrieve SSH public key into authorized_keys for EC2 instances
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# vim:set ts=4 sw=4 et ai: | |
# Retrieve the SSH public key and install it for subsequent login attempts. | |
AUTHORIZED_KEYS=/root/.ssh/authorized_keys | |
TMP_KEY=/tmp/openssh_id.pub | |
CURL=/usr/bin/curl | |
CURLOPTS="--retry 3 --retry-delay 2 --silent --fail -o $TMP_KEY" | |
KEY_URL=http://169.254.169.254/1.0/meta-data/public-keys/0/openssh-key | |
KEY_FILE=/mnt/openssh_id.pub | |
SUCCESS=0 | |
ATTEMPT=0 | |
MAX_ATTEMPTS=10 | |
if [ ! -d `dirname $AUTHORIZED_KEYS` ]; then | |
mkdir -p -m 700 `dirname $AUTHORIZED_KEYS` | |
fi | |
while [ $SUCCESS -eq 0 -a $ATTEMPT -lt $MAX_ATTEMPTS ] ; do | |
# attempt to retrieve the SSH public key and install it | |
if [ -f $KEY_FILE ] ; then | |
cat $KEY_FILE > $AUTHORIZED_KEYS | |
echo "SSH key added to $AUTHORIZED_KEYS from $KEY_FILE" | |
SUCCESS=1 | |
else | |
$CURL $CURLOPTS $KEY_URL | |
if [ $? -eq 0 -a -f $TMP_KEY ]; then | |
cat $TMP_KEY > $AUTHORIZED_KEYS | |
echo "SSH key added to $AUTHORIZED_KEYS from $KEY_URL" | |
rm -f $TMP_KEY | |
SUCCESS=1 | |
fi | |
fi | |
# print out status and wait for a bit if we failed | |
ATTEMPT=$(($ATTEMPT + 1)) | |
if [ $SUCCESS -eq 1 ]; then | |
echo "SSH key retrieval attempt $ATTEMPT failed" | |
sleep 5 | |
fi | |
done | |
# either we got it or we just gave up | |
if [ -f $AUTHORIZED_KEYS ]; then | |
chmod 600 $AUTHORIZED_KEYS | |
else | |
echo "-=[ FATAL ]=- SSH key could not be retrieved!!!" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment