Skip to content

Instantly share code, notes, and snippets.

@DocX
Last active September 5, 2023 12:58
Show Gist options
  • Save DocX/80e92f4c4c55d9ab6c4a to your computer and use it in GitHub Desktop.
Save DocX/80e92f4c4c55d9ab6c4a to your computer and use it in GitHub Desktop.
Connect to bash inside running ECS container by cluster and service name
#!/bin/bash
CLUSTER=$1
SERVICE=$2
if [ -z "$CLUSTER" -o -z "$SERVICE" ]; then
echo "Usage:"
echo "ecs-console cluster-name service-name"
exit 1
fi
TASK_ID=$( aws ecs list-tasks --cluster=$CLUSTER --service-name=$SERVICE --output json | jq -r '.taskArns[0]' )
CONTAINER_INSTANCE_ID=$( aws ecs describe-tasks --cluster=$CLUSTER --tasks $TASK_ID --output json | jq -r '.tasks[0].containerInstanceArn' )
EC2_INSTANCE=$( aws ecs describe-container-instances --cluster=staging --container-instances $CONTAINER_INSTANCE_ID --output json | jq -r '.containerInstances[0].ec2InstanceId' )
EC2_IP=$( aws ec2 describe-instances --instance-ids $EC2_INSTANCE --output json | jq -r '.Reservations[0].Instances[0].PublicIpAddress' )
echo Connecting to: $EC2_IP
ssh -i $ECS_PEM_FILE ec2-user@$EC2_IP -t 'bash -c "docker exec -it $( docker ps -a -q -f name=ecs-'$SERVICE' | head -n 1 ) bash"'
@sashazykov
Copy link

It doesn't if json is not a default output format. Add --output json parameter to all aws commands.

@sandsu
Copy link

sandsu commented Jan 14, 2017

EC2_INSTANCE=$( aws ecs describe-container-instances --cluster=staging --container-instances $CONTAINER_INSTANCE_ID --output json | jq -r '.containerInstances[0].ec2InstanceId' )
should be
EC2_INSTANCE=$( aws ecs describe-container-instances --cluster=$CLUSTER --container-instances $CONTAINER_INSTANCE_ID --output json | jq -r '.containerInstances[0].ec2InstanceId' )

@geekosphere-net
Copy link

On line 14 you have --cluster=staging it should be --cluster=$CLUSTER
Also I changed line 15 from PublicIpAddress to PrivateIpAddress as not all servers will have a public IP
Cool script, thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment