#!/bin/bash
# ---------------------------------------------------------------------------------------------------
# Lists all the instances in a given region and upon user selection opens an interactive SSM session
# with that instance.
# ---------------------------------------------------------------------------------------------------
# Stop immediately if anything goes wrong, let's not create too much
# mess if John's shell is poor
set -eo pipefail
# Find & Import all the supporting functions from the supporting folder
# Get the directory of the current script to figure out where the
# Supporting funcs are
IMPORT_DIR=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)
for script in ${IMPORT_DIR}/supporting-funcs/*.sh; do
if [[ -f "$script" ]]; then
source "$script"
fi
done
usage() {
echo
title "ssm"
section "----------------------------------"
echo "This script will open an SSH session to"
echo "an EC2 instance you select. It finds all"
echo "EC2 instances in a given region of the"
echo "AWS account of the supplied profile."
section "----------------------------------"
usage_text "Usage:" "ssm [-p profile] [-r region]"
echo " $(option "-p profile") AWS profile to use"
echo " $(option "-r region") AWS region to use"
echo
exit 0
}
# Add a check to see if the script is being sourced or executed
if [[ "${BASH_SOURCE[0]}" != "${0}" ]]; then
usage
fi
# Parse flags
while getopts ":p:r:" opt; do
case ${opt} in
p)
profile=$OPTARG
;;
r)
region=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" >&2
usage
;;
:)
echo "Option -$OPTARG requires an argument." >&2
usage
;;
esac
done
# Main script
profile=$(get_param_or_env "$profile" "AWS_PROFILE" "Enter the AWS profile to use")
region=$(get_param_or_env "$region" "AWS_REGION" "Enter the AWS region (e.g., us-west-2)")
export AWS_PROFILE="$profile"
export AWS_REGION="$region"
# List instances with fixed-width columns
instances=$(list_instances)
if [ -z "$instances" ]; then
echo "No running instances found."
exit 1
fi
echo "Running instances in region $region:"
printf "%-5s %-20s %-20s %-20s %-20s\n" "Index" "Name" "InstanceId" "InstanceType" "PrivateIpAddress"
i=1
while read -r line; do
name=$(echo "$line" | awk '{print $1}')
instance_id=$(echo "$line" | awk '{print $2}')
instance_type=$(echo "$line" | awk '{print $3}')
private_ip=$(echo "$line" | awk '{print $4}')
printf "%-5s %-20s %-20s %-20s %-20s\n" "$i" "$name" "$instance_id" "$instance_type" "$private_ip"
((i++))
done <<< "$instances"
read -p "Select an instance by index: " selection
instance_id=$(echo "$instances" | sed -n "${selection}p" | awk '{print $2}')
name=$(echo "$instances" | sed -n "${selection}p" | awk '{print $1}')
if [ -z "$instance_id" ]; then
echo "Invalid selection."
exit 1
fi
echo "Starting Interactive SSM session with instance $instance_id..."
start_interactive_ssm_session "$instance_id" "$name"