export AWS_PROFILE And AWS_REGION before executing .
#!/bin/bash
#+---------------------------------------------------------------------------------------------+
# SCRIPT DATE : 26/01/2023 |
# AUTHOR : Praveen HA |
# MODIFIED DATE : 26/01/2023 |
# |
# 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 |
# ./ccoe-connect.sh <instanceid>/<Instance Private IP>/<Instance Tag> / |
#<Instancetag Value> <Instance Tag key> |
#----------------------------------------------------------------------------------------------+
#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 "${GREEN} [Syntax]: $(basename "$0") <AWS Instance ID / Instance IP / Instance Tag>"
}
if [[ "$1" == "--help" ]]; then
Help
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
# aws --region "$region" ssm start-session --target "$instance_id" #--profile "$profile"
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
Comments
Post a Comment