Last active
April 10, 2018 10:51
-
-
Save ajardin/b94c7203284003b13f97f61b7d472ba2 to your computer and use it in GitHub Desktop.
Make the SSH connection to EC2 instances easier by requiring only tag values instead of IP addresses.
This file contains 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
#!/usr/bin/env bash | |
set -euo pipefail | |
# ====================================================================================================================== | |
# Make the SSH connection to EC2 instances easier by requiring only tag values instead of IP addresses. | |
# | |
# Usage: | |
# bash aws-connect.sh <environment> <bastion|apache|nginx|...> <index> | |
# | |
# Examples: | |
# SSH to the bastion: bash aws-connect.sh <environment> bastion | |
# SSH to the first Apache instance: bash aws-connect.sh <environment> apache | |
# SSH to the second Apache instance: bash aws-connect.sh <environment> apache 2 | |
# ====================================================================================================================== | |
# Validate arguments passed to the script | |
if [[ ($# -eq 2 || $# -eq 3) && -n "$1" && -n "$2" ]]; then | |
environment="$1" | |
instance_type="$2" | |
if [[ $# -eq 3 && $3 =~ ^[0-9]+$ ]]; then | |
instance_index=$(( $3 - 1 )) | |
else | |
instance_index=0 | |
fi | |
else | |
echo "Usage: bash aws-connect.sh <environment> <bastion|apache|nginx|...> <index>" | |
exit 1 | |
fi | |
# Retrieve the bastion public IP address | |
bastion_ip=$(aws ec2 describe-instances \ | |
--filters "Name=tag:Environment,Values=${environment}" "Name=tag:Name,Values=${environment}-bastion" "Name=instance-state-name,Values=running" \ | |
| jq -r ".Reservations[0].Instances[0].PublicIpAddress" | |
) | |
# Retrieve the remote private IP address | |
remote_ip=$(aws ec2 describe-instances \ | |
--filters "Name=tag:Environment,Values=${environment}" "Name=tag:Name,Values=${environment}-${instance_type}" "Name=instance-state-name,Values=running" \ | |
| jq -r ".Reservations[${instance_index}].Instances[0].PrivateIpAddress" | |
) | |
# Execute the SSH connection | |
if [[ "${instance_type}" == "bastion" ]]; then | |
ssh ec2-user@"${bastion_ip}" -A | |
else | |
ssh ec2-user@"${bastion_ip}" -A -t ssh ec2-user@"${remote_ip}" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment