Created
December 19, 2019 09:16
-
-
Save JCash/80fe2096e98211c07acd0321920b86b5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#################################################### | |
# Connect to running AWS instances using tag names # | |
# Author: [email protected] # | |
#################################################### | |
PEM_FILE="$HOME/.ssh/aws.pem"; | |
DEFAULT_USERNAME="ubuntu"; | |
function print_running_instances { | |
printf "Running instances:\n"; | |
aws ec2 describe-instances --filter "Name=instance-state-name,Values=running" --query "Reservations[*].Instances[*].[Tags[?Key=='Name'].Value[],PublicIpAddress]" --output=text \ | |
| xargs -n2 \ | |
| awk -v bold=$(tput bold) -v normal=$(tput sgr0) '{print bold $2 normal " (" $1 ")"}' \ | |
| column -t \ | |
| sort; | |
} | |
function connect_to_instance { | |
ip=$(aws ec2 describe-instances --filter "Name=tag:Name,Values=$1" "Name=instance-state-name,Values=running" --query "Reservations[*].Instances[*].PublicIpAddress" --output=text); | |
printf "Connecting to $ip\n" | |
if [ -z "$ip" ]; then | |
printf "Could not find a running instance tagged '$1'\n"; | |
print_running_instances; | |
exit 1; | |
fi | |
ssh -i $PEM_FILE $username@$ip; | |
} | |
if [ $# -eq 0 ] | |
then | |
printf "Usage: $0 <instance name> [username]\n\n"; | |
print_running_instances; | |
printf "\nusername defaults to 'ubuntu'\n\n"; | |
exit 1; | |
fi | |
if [ ! -r $PEM_FILE ] | |
then | |
printf "The private key file $PEM_FILE is missing or unreadable. If you have used a different filename, please rename it or run:\n\n ln -s <path to pem file> $PEM_FILE\n\n"; | |
exit 1; | |
fi | |
username=$DEFAULT_USERNAME; | |
if [ $# -eq 2 ] | |
then | |
username=$2; | |
fi | |
connect_to_instance $1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment