Skip to content

Instantly share code, notes, and snippets.

@evertonfraga
Created August 1, 2024 20:38
Show Gist options
  • Save evertonfraga/cb1e9c23faf67482502697a9c4950aae to your computer and use it in GitHub Desktop.
Save evertonfraga/cb1e9c23faf67482502697a9c4950aae to your computer and use it in GitHub Desktop.
#!/bin/bash
# Author: Everton Fraga <effraga@amazon.com>
# Check if a stack name was provided
if [ $# -eq 0 ]; then
echo "Please provide a CloudFormation stack name."
echo "Usage: $0 <stack-name>"
exit 1
fi
# Store the stack name
STACK_NAME="$1"
# Get the list of EC2 instance IDs associated with the stack
INSTANCE_IDS=$(aws cloudformation describe-stack-resources \
--stack-name "$STACK_NAME" \
--query "StackResources[?ResourceType=='AWS::EC2::Instance'].PhysicalResourceId" \
--output text)
# Check if any instances were found
if [ -z "$INSTANCE_IDS" ]; then
echo "No EC2 instances found for stack: $STACK_NAME"
exit 1
fi
# Get the first instance ID
FIRST_INSTANCE_ID=$(echo $INSTANCE_IDS | awk '{print $1}')
echo "Connecting to instance: $FIRST_INSTANCE_ID"
# Start an SSM session with the first instance
echo "aws ssm start-session --target \"$FIRST_INSTANCE_ID\""
aws ssm start-session --target "$FIRST_INSTANCE_ID"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment