Skip to content

Instantly share code, notes, and snippets.

@leandrosiow
Last active February 9, 2020 22:06
Show Gist options
  • Select an option

  • Save leandrosiow/2175bb8a4fb5a1a7ce8d0e9d61500b2e to your computer and use it in GitHub Desktop.

Select an option

Save leandrosiow/2175bb8a4fb5a1a7ce8d0e9d61500b2e to your computer and use it in GitHub Desktop.
This little script helps you SSH to your EC2 instance via an instance-id. You will still need to have your pem files in the .ssh folder.
ec2ssh()
{
if [[ ! -z "$1" ]]; then
# echo "cfn"
INSTANCE_ID_INPUT=$1
else
echo -n "Enter Instance ID: "
read INSTANCE_ID_INPUT
fi
# Grab Public IP of Instance
PUBLIC_IP="$(aws ec2 describe-instances --instance-id "$INSTANCE_ID_INPUT" | grep PublicIpAddress | awk -F\" '{print $4}')"
if [[ ! -z "$PUBLIC_IP" ]]; then
# If $PUBLIC_IP is not empty
echo -e "PublicIPAddress:\t"$PUBLIC_IP
KEY_NAME="$(aws ec2 describe-instances --instance-id "$INSTANCE_ID_INPUT" | grep KeyName | awk -F\" '{print $4}')"
echo -e "Using SSH Key:\t\t"$KEY_NAME
echo -e "Attempting to connect to "$INSTANCE_ID_INPUT" at "$PUBLIC_IP".\n"
ssh -i ~/.ssh/$KEY_NAME.pem ec2-user@$PUBLIC_IP
else
echo "This instance "$INSTANCE_ID_INPUT" does not have a Public IP."
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment