Skip to content

Instantly share code, notes, and snippets.

@dylansmith
Last active October 27, 2015 06:11
Show Gist options
  • Save dylansmith/1872a8a7cce2a433465c to your computer and use it in GitHub Desktop.
Save dylansmith/1872a8a7cce2a433465c to your computer and use it in GitHub Desktop.
ec2 ssh access by "name" tag and instance number, with optional command to pass
#!/bin/bash
# USAGE:
# ./ec2ssh.sh <tag:name> <instance_num> [<remote_command>]
if [ $# -lt 2 ]
then
echo "Usage: `basename $0` <tag:name> <instance_num>"
exit 1
fi
stack_name=$1
instance_num=$2
cmd=$3
pem_env_var="AWS_PEM"
pem_path=${!pem_env_var}
if [ $instance_num -lt 1 ]
then
echo "Instance number should be >= 1"
exit 1
fi
if [ -z $pem_path ]
then
echo "Set a $pem_env_var environment variable to the path of your pem key"
exit 1
fi
user="ec2-user"
filters="{\"Name\":\"tag:Name\", \"Values\":[\"$stack_name\"]}"
query="Reservations[*].Instances[*].PublicIpAddress"
echo "Fetching instance IPs..."
ips=($(aws ec2 describe-instances --filters "$filters" --query="$query" | egrep -o "(\d+\.?)+"))
for i in "${!ips[@]}"; do
echo "$i: ${ips[$i]}"
done
num_ips=${#ips[@]}
if [ $instance_num -gt $num_ips ]
then
echo "Requested instance $instance_num, but only $num_ips instances were found"
exit 1
fi
ip=${ips[instance_num-1]}
echo "Logging in: $user@$ip..."
ssh -i $pem_path $user@$ip $cmd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment