Skip to content

Instantly share code, notes, and snippets.

@PGBI
Last active March 1, 2023 21:03
Show Gist options
  • Save PGBI/10b701ac962731e9aa8619adbe93cb3f to your computer and use it in GitHub Desktop.
Save PGBI/10b701ac962731e9aa8619adbe93cb3f to your computer and use it in GitHub Desktop.
Helper to start an SSM session in an ec2 instance knowing its name
# Starts an SSM session in an EC2 instance
#
# Prerequesites: have the following tools installed:
# - awscli
# - jq
# - session-manager-plugin (https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html)
#
# Usage: start_ssm_session <instance ID | IP | Name>
# Examples:
# start_ssm_session i-0041d4a4bd0fdcb2d
# start_ssm_session 10.0.103.41
# start_ssm_session "citus-worker-*"
export AWS_DEFAULT_OUTPUT="json"
start_ssm_session() {
if [ -z "$1" ]; then
echo "Instance name (wildcard accepted):"
read -r NAME
else
NAME="$1"
fi
# searching by name
INSTANCES=$(aws ec2 describe-instances --filters "Name=tag:Name,Values=${NAME}" "Name=instance-state-name,Values=running" --query "Reservations[].Instances[].[InstanceId,Tags[?Key=='Name'].Value[] | [0]]")
INSTANCE_COUNT=$(echo "$INSTANCES" | jq length)
if [ "$INSTANCE_COUNT" -eq 0 ]; then
# searching by internal IP
INSTANCES=$(aws ec2 describe-instances --filters "Name=private-ip-address,Values=${NAME}" "Name=instance-state-name,Values=running" --query "Reservations[].Instances[].[InstanceId,Tags[?Key=='Name'].Value[] | [0]]")
INSTANCE_COUNT=$(echo "$INSTANCES" | jq length)
fi
if [ "$INSTANCE_COUNT" -eq 0 ]; then
# searching by instance-id
INSTANCES=$(aws ec2 describe-instances --instance-ids "$NAME" --query "Reservations[].Instances[].[InstanceId,Tags[?Key=='Name'].Value[] | [0]]")
INSTANCE_COUNT=$(echo "$INSTANCES" | jq length)
fi
if [ "$INSTANCE_COUNT" -eq 0 ]; then
echo "Couldn't find any running instance with this name."
return
elif [ "$INSTANCE_COUNT" -gt 1 ]; then
for ((i=0; i<$INSTANCE_COUNT; i++)); do
ID=$(echo "$INSTANCES" | jq -r ".[$i][0]")
NAME=$(echo "$INSTANCES" | jq -r ".[$i][1]")
echo "[${i}] $ID - $NAME"
done
echo "Which one?"
read INDEX
else
INDEX=0
fi
INSTANCE_ID=$(echo "$INSTANCES" | jq -r ".[$INDEX][0]")
aws ssm start-session --target "$INSTANCE_ID"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment