Lately I've been doing some experimentation on a temporary Amazon EC2 instance. So far I have been starting each session by running ec2-run-instances
on the command line to boot the instance, then running ec2-describe-instances
to get the host name, and finally connecting via SSH.
Scott Moser's post inspired me to automate the process as well as verify the SSH fingerprint of the new instance:
#!/bin/sh # start an EC2 micro instance running the 32-bit, EBS-backed Amazon Linux AMI RUN=`ec2-run-instances ami-3bc9997e -k KEY -t t1.micro -z us-west-1c` # retrieve the instance ID from the output INSTANCE=`echo $RUN | grep -E -o ' i-[a-f0-9]+' | sed 's/INSTANCE *//'` # seems to take about 3 to 4 minutes for SSH fingerprints to show # up in the output. wait for 2 and a half minutes, then start polling output echo "Waiting 150s for $INSTANCE to boot" sleep 150 while [ 1 ] do FINGERPRINTS=`ec2-get-console-output $INSTANCE | egrep -m 1 -o '([0-9a-f][0-9a-f]:){15}[0-9a-f][0-9a-f]'` if [ "$FINGERPRINTS" = "" ] then sleep 30 echo "Booting..." else break fi done echo "Expected fingerprints are $FINGERPRINTS" # get hostname for the instance HOST=`ec2-describe-instances | grep -m 1 $INSTANCE | egrep -o 'ec2(-[0-9]+){4}.us-west-1.compute.amazonaws.com'` echo "Host is $HOST" ssh-keyscan $HOST 2>/dev/null > host.key ssh-keygen -lf host.key > host.fingerprint read len ACTUAL_FINGERPRINTS host rsa < host.fingerprint echo "Actual fingerprints are $ACTUAL_FINGERPRINTS" if [ "$ACTUAL_FINGERPRINTS" = "$FINGERPRINTS" ] then echo "Fingerprints match, adding to known hosts" ssh-keygen -q -R "$HOST" ssh-keygen -q -H -f host.key cat host.key >> ~/.ssh/known_hosts echo "Ready to connect" echo "ssh -i PATH_TO_KEY ec2-user@$HOST" else echo "Fingerprints do not match" fi shred -u host.key host.fingerprint
Thanks Scott!