Skip to content

Instantly share code, notes, and snippets.

@akheron
Created October 19, 2012 11:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akheron/3917688 to your computer and use it in GitHub Desktop.
Save akheron/3917688 to your computer and use it in GitHub Desktop.
Connect to Amazon EC2 instances
#!/bin/sh
#
# Look up the public IP address of an Amazon EC2 instance via
# the Amazon API, and connect to it using ssh.
# Defaults
region=eu-west-1
identity_file=~/amazon/identity.pem
username=ubuntu
usage() {
cat >&2 <<EOF
usage: $0 [options] name
Connects to the given instance via ssh.
Options:
-n Dry-run; print the ssh command line instead of
actually connecting
-r REGION Amazon AWS region to connect to [$region]
-i IDENTITY_FILE
SSH identity file [$identity_file]
-u USERNAME SSH username [$username]
Arguments:
name Value of the Name tag of the instance
EOF
exit 2
}
while getopts nr:i:u: f; do
case $f in
n) dryrun=1 ;;
r) region=$OPTARG ;;
i) identity_file=$OPTARG ;;
u) username=$OPTARG ;;
\?) usage
esac
done
shift $(expr $OPTIND - 1)
[ $# -ne 1 ] && usage
[ -z "$1" ] && usage
name=$1
instance=$(ec2din --region $region -F "tag:Name=$name")
if [ -z "$instance" ]; then
echo >&2 "Instance $name was not found in region $region"
exit 1
fi
ip=$(echo "$instance" | grep ^INSTANCE | awk '{ print $4 }' | grep compute.amazonaws.com)
cmd="ssh -i $identity_file $username@$ip"
if [ -n "$dryrun" ]; then
echo $cmd
else
exec "$cmd"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment