Skip to content

Instantly share code, notes, and snippets.

@henrikenblom
Last active June 5, 2018 10:00
Show Gist options
  • Save henrikenblom/73471dc61cfa553e73d228514876b0d2 to your computer and use it in GitHub Desktop.
Save henrikenblom/73471dc61cfa553e73d228514876b0d2 to your computer and use it in GitHub Desktop.
Connect to running AWS instances using tag names
#!/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;
}
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