Skip to content

Instantly share code, notes, and snippets.

@ajardin
Created August 21, 2020 18:35
Show Gist options
  • Save ajardin/5a1bd9ce8bb29127fed4ba031fa216eb to your computer and use it in GitHub Desktop.
Save ajardin/5a1bd9ce8bb29127fed4ba031fa216eb to your computer and use it in GitHub Desktop.
Connecting to EC2 instances without a headache
#!/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