Skip to content

Instantly share code, notes, and snippets.

@HQarroum
Last active April 6, 2023 07:42
Show Gist options
  • Save HQarroum/ab7375b7aed1ca98a8fe331d69d7252b to your computer and use it in GitHub Desktop.
Save HQarroum/ab7375b7aed1ca98a8fe331d69d7252b to your computer and use it in GitHub Desktop.
A Bash script to establish an SSM tunnel given an EC2 machine name, private DNS name, or identifier.
#!/bin/bash
set -e
if [ ! "$1" ]
then
echo "Expected a hostname of the instance as a parameter."
exit 1
fi
# Input variables.
HOSTNAME="$1"
SSH_PORT="${2:-22}"
# Matching instance names, starting by `aws-`.
if [[ $HOSTNAME = aws-* ]]; then
INSTANCE_ID=$(aws ec2 describe-instances \
--filter "Name=tag:Name,Values=$HOSTNAME" \
--query "Reservations[].Instances[?State.Name == 'running'].InstanceId[]" \
--output text)
fi
# Matching instance identifiers, starting by `i-` or `mi-`.
if [[ $HOSTNAME = i-* || $HOSTNAME = mi-* ]]; then
INSTANCE_ID=$HOSTNAME
fi
if [[ ! $INSTANCE_ID ]]; then
echo "Could not resolve instance identifier for hostname '$HOSTNAME'."
exit 1
fi
# Creating the SSM tunnel once we've resolved the
# instance identifier.
aws ssm start-session \
--target $INSTANCE_ID \
--document-name AWS-StartSSHSession \
--parameters "portNumber=$SSH_PORT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment