Skip to content

Instantly share code, notes, and snippets.

@javipolo javipolo/ec2ssh
Last active May 28, 2018

Embed
What would you like to do?
Connect to ec2 instances using either InstanceId, Name tag or Ip address, using multiple ssh keys as identities
#!/bin/bash
# Connect to ec2 instances using either InstanceId, Name tag or Ip address
# We try all the ssh keys available in a directory supplied by the env variable SSH_KEYDIR
# Usage:
# - ec2ssh i-123124123123
# - ec2ssh [-n 2] name_tag
# - ec2ssh IP
colors=1
opts="-v"
user="ubuntu"
[ "$1" == "-n" ] && { host_num=$2; shift; shift; }
host=$1
shift
show_host_list(){
if [ "$colors" == "1" ]; then
c_not='\e[38;5;204m'
c_this='\e[1;38;5;121m'
c_off='\e[0m'
else
c_not=""
c_this=""
c_off=""
fi
for h in $hosts; do
if [ "$h" == "$host" ]; then
show_hosts="$show_hosts --> ${c_this}${h}${c_off} <--"
else
show_hosts="$show_hosts ${c_not}${h}${c_off}"
fi
done
echo -e "HOSTS: $show_hosts"
}
if echo $host | grep -e "^i-" -q; then
# This is a instance ID
host=$(aws ec2 describe-instances \
--filter "Name=instance-state-name,Values=running" \
--query "Reservations[*].Instances[*].PublicIpAddress" \
--instance-id $host --output text)
hosts=$host
elif echo $host | grep -P "^([0-9]+\.){3}[0-9]+" -q; then
# Or an IP address
hosts=$host
elif [ "$(dig +short $host)" ]; then
# or a DNS name that resolves
hosts=$host
else
# Everything else should be an instance name
hosts=$(aws ec2 describe-instances \
--filter "Name=instance-state-name,Values=running" \
--filter "Name=tag:Name,Values=$host" \
--query "Reservations[*].Instances[*].PublicIpAddress" \
--output text \
| sort -n )
host=$(echo "$hosts" | head -n${host_num:-1} | tail -n1)
fi
show_host_list
keys=$SSH_KEYDIR/*
for key in $keys; do
keylist="-i $key $keylist"
done
ssh $opts $keylist ${user}@${host} $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.