Skip to content

Instantly share code, notes, and snippets.

@jenyayel
Created December 17, 2018 09:51
Show Gist options
  • Save jenyayel/8d5089c47019e2da955a61e7c69818ce to your computer and use it in GitHub Desktop.
Save jenyayel/8d5089c47019e2da955a61e7c69818ce to your computer and use it in GitHub Desktop.
Retrieves EC2 DNS by instance name and opens SSH
#!/bin/bash
set -e
command -v aws >/dev/null 2>&1 || { echo >&2 "AWS CLI required. Please install from https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html"; exit 1; }
# get the name of EC2 instance from 1st argument
if [ -z "$1" ]
then
echo "Instance name is required"
exit 1
else
NAME=$1
fi
# get the 2nd optional argument for path of key
if [ -z "$2" ]
then
PRIVATE="/home/jenya/.ssh/id_rsa"
else
PRIVATE=$2
fi
# validate private key file exists
if [ ! -f $PRIVATE ]; then
echo "No file with private key found at '${PRIVATE}'"
exit 1
fi
printf "Getting DNS name of ${NAME}..."
DNS=$(aws ec2 describe-instances --filters 'Name=tag:Name,Values='${NAME} --query 'Reservations[*].Instances[*].[PublicDnsName]' --output text)
# validate that instance was found for provided name
if [ -z "$DNS" ]
then
printf "\nNo instance found with name '${NAME}'\n"
exit 1
else
echo " '${DNS}'"
fi
# the actual SSH to the instance
ssh -i ${PRIVATE} ubuntu@${DNS}
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment