Streamlining AWS EC2 Connectivity with SSM: A Comprehensive Guide

Praveen HAPraveen HA
3 min read

Table of contents

Introduction:

Connecting EC2 instance with Tag or Instance ID or Name Tag or Tag value and tag key.

In the dynamic landscape of cloud computing, managing and connecting to Amazon EC2 instances is a crucial aspect of day-to-day operations. Amazon Web Services (AWS) offers a powerful solution for secure and efficient instance access through the Systems Manager (SSM) Session Manager. In this comprehensive guide, we explore how to streamline and simplify the process using a Bash script, providing a seamless experience for AWS users.

This comprehensive guide unveils a Bash script designed to empower users with versatile access options. From instance IDs and IP addresses to tags and key values, this script offers a holistic approach to EC2 connectivity using AWS Systems Manager (SSM).

The script is designed to simplify the process of connecting to an EC2 instance using AWS SSM Session Manager by allowing users to specify an Instance ID, IP address, or Tag.

Prerequisites:

Before running the script, ensure you have the following prerequisites in place:

1. AWS CLI Installed: Make sure the AWS Command Line Interface (CLI) is installed on your system, and you have configured your AWS credentials using `aws configure`.

2. AWS SSM Session manager Plugin: Ensure that the SSM session manager plugin is installed for AWS CLI. You can install it please use below link:
https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html 
AWS Profile and Region: Export your AWS profile and region before running the script. Use the following commands, replacing <your_profile> and <your_region> with your actual AWS profile and region:
export AWS_PROFILE=<your_profile>
export AWS_REGION=<your_region>
#!/bin/bash
#+---------------------------------------------------------------------------------------------+
# SCRIPT DATE   : 19/01/2024                                                                   |
# AUTHOR        : Praveen HA                                                                   |
# MODIFIED DATE : 19/01/2024                                                                   |    
#                                                                                              |
# Supported OS : CentOS7.x, RHEL8.x , RHEL9.x , Ubuntu22.x Ubuntu20.x x64 and ARM Architecture |
# DESCRIPTION                                                                                  |
# This script will establishes Session through SSM                                             |
# Execution step                                                                               |
# ./aws-ssm-ec2-connect.sh <instanceid>/<Instance Private IP>/<Instance Tag>                          |
#----------------------------------------------------------------------------------------------+
#Set the AWS region
#region="us-west-2"
# Get the session manager profile
#profile="my-profile"
BLUE='\033[0;34m'
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'
CLEAR_LINE='\r\033[K'
# Get input
input=$1
# Get tag key
tag_key=${2:-"Name"}

right_now ()
{
    echo "$(date -u "+%a %b %d UTC %Y %T:%3N")"
}

Help()
{
   # Display Help
   echo -e "\e[32m
   AWS Session manager EC2 Connect Tool from Praveen HA.
   -------------------------------------------------------------------------------
    \e[0m"

   echo -e "${GREEN} [Syntax]: $(basename "$0") <AWS Instance ID / Instance IP / Instance Tag>"
  }

if [[ "$1" == "--help" ]]; then
    Help
    exit 0
fi
if [[ "$1" == "--version" ]]; then
    echo "Version 2023.10"
    exit 0
fi


echo -e "${BLUE} [INFO]: $(right_now) Validating Inputs"
echo -e "${NC}"
# check if the input is valid instance id or ip or tag
if [[ $input =~ ^i-[0-9a-f]{8}$|^i-[0-9a-f]{17}$ ]] || [[ $input =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] || [[ $input =~ ^[a-zA-Z0-9_-]*$ ]]; then 
    if [[ $input =~ ^i-[0-9a-f]{8}$|^i-[0-9a-f]{17}$ ]]; then
      echo -e "${GREEN} [INFO]: $(right_now) Validating Instance-ID Provided"
      instance_id=$input
    elif [[ $input =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
      echo -e "${GREEN} [INFO]: $(right_now) Validating Instance Ip Address Provided "
      instance_id=$(aws ec2 describe-instances --filter "Name=private-ip-address,Values=$input" --region $AWS_REGION --query 'Reservations[*].Instances[*].InstanceId' --output text)
    elif [[ $input =~ ^[a-zA-Z0-9_-]*$ ]]; then
      echo -e "${GREEN} [INFO]: $(right_now) Validating...."
      instance_id=$(aws ec2 describe-instances --filter "Name=tag:$tag_key,Values=$input" --region $AWS_REGION --query 'Reservations[*].Instances[*].InstanceId' --output text)
  fi

if [[ $instance_id ]]; then
    echo -e "${CLEAR_LINE}${NC}"
    aws ssm start-session --target "$instance_id" --region $AWS_REGION #--profile "$profile"
  else
    echo -e "${RED} [ERROR]: $(right_now) Not Able to find the Instance with Provided Input"
    echo -e "${RED} [ERROR]: $(right_now) Please provide valid Inputs ..Check your input valid Instance-ID, Instance IP, Instance Tag."
    Help
    echo -e "${NC}"

fi
else
    echo -e "${RED} [ERROR]: $(right_now) Invalid Input Provided"
    echo -e "${RED} [ERROR]: $(right_now) Please provide valid Inputs ..Check your input valid Instance-ID, Instance IP, Instance Tag."
    Help
    echo -e "${NC}"

fi
Examples :

Example 1: Connecting by Instance ID

   bash script.sh i-0123456789abcdef0

Example 2: Connecting by IP Address

     bash script.sh 192.168.1.1

Example 3: Connecting by Name Tag Value

      bash script.sh my-instance-tag

Example 4: Specifying Tag Key and Value

     bash script.sh my-instance-tag Environment

     bash script_name.sh <tagvalue> <tagkey>
0
Subscribe to my newsletter

Read articles from Praveen HA directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Praveen HA
Praveen HA