Skip to content

Instantly share code, notes, and snippets.

@Maks3w
Last active February 14, 2021 20:46
Show Gist options
  • Save Maks3w/28f9523bee426dc443830afbbb9502f4 to your computer and use it in GitHub Desktop.
Save Maks3w/28f9523bee426dc443830afbbb9502f4 to your computer and use it in GitHub Desktop.
This script locate and SSH into an EC2 instance executing the given ECS service
#!/usr/bin/env bash
if [[ $# -lt 2 ]]; then
echo "Invalid arguments $0 <cluster> <service>"
exit 1
fi
cluster=$1
service=$2
aws_ecs_id=`aws ecs list-container-instances --cluster $cluster --filter "task:group == service:$service" --query 'containerInstanceArns[0]' --output text`
if [[ $? -ne 0 || $aws_ecs_id = "None" ]]; then
echo "ECS service not found for service '$service' in cluster '$cluster'"
exit 2
fi
aws_ec2_id=`aws ecs describe-container-instances --cluster $cluster --container-instances $aws_ecs_id --query 'containerInstances[0].[ec2InstanceId]' --output text`
[[ $? -ne 0 ]] && echo "ECS instance not found for service '$service' in cluster '$cluster'" && exit 3
aws ssm start-session --target $aws_ec2_id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment