Skip to content

Instantly share code, notes, and snippets.

@SafeEval
Created May 30, 2025 20:56
Show Gist options
  • Save SafeEval/41cb156b9935ed7d9f89693e4079adc4 to your computer and use it in GitHub Desktop.
Save SafeEval/41cb156b9935ed7d9f89693e4079adc4 to your computer and use it in GitHub Desktop.
ECS Exec Shell — Shelling into an AWS Fargate container
#!/bin/bash
# Set CLUSTER_NAME and SERVICE_NAME env vars.
# Get the container task ID.
TASK_ID=$(aws ecs list-tasks \
--cluster "$CLUSTER_NAME" \
--desired-status RUNNING \
--output text \
--query 'taskArns[0]' | awk -F/ '{print $NF}')
# Verify that ECS Exec is enabled.
aws ecs describe-tasks \
--cluster "$CLUSTER_NAME" \
--tasks "$TASK_ID" \
| grep 'enableExecuteCommand'
#!/bin/bash
# Set CLUSTER_NAME and SERVICE_NAME env vars.
# Enable container insights for the cluster.
aws ecs update-cluster-settings \
--cluster "$CLUSTER_NAME" \
--settings name=containerInsights,value=enabled \
> /dev/null
# Configure execution command logging.
aws ecs update-cluster \
--cli-input-json '{
"cluster": "'"$CLUSTER_NAME"'",
"configuration": {
"executeCommandConfiguration": {
"logging": "DEFAULT"
}
}
}' \
> /dev/null
# Get the container task ID.
TASK_ID=$(aws ecs list-tasks \
--cluster "$CLUSTER_NAME" \
--desired-status RUNNING \
--output text \
--query 'taskArns[0]' | awk -F/ '{print $NF}')
aws ecs update-service \
--cluster "$CLUSTER_NAME" \
--service "$SERVICE_NAME" \
--force-new-deployment \
--enable-execute-command \
> /dev/null
# Wait for the ECS service to update.
sleep 360
# Verify that ECS Exec is enabled.
aws ecs describe-tasks \
--cluster "$CLUSTER_NAME" \
--tasks "$TASK_ID" \
| grep 'enableExecuteCommand'
#!/bin/bash
# Set CLUSTER_NAME and SERVICE_NAME env vars.
# Get the container task ID.
TASK_ID=$(aws ecs list-tasks \
--cluster "$CLUSTER_NAME" \
--desired-status RUNNING \
--output text \
--query 'taskArns[0]' | awk -F/ '{print $NF}')
CONTAINER_NAME=$(aws ecs describe-tasks \
--cluster "$CLUSTER_NAME" \
--tasks "$TASK_ID" \
--query 'tasks[0].containers[0].name' \
--output text)
aws ecs execute-command \
--cluster "$CLUSTER_NAME" \
--task "$TASK_ID" \
--container "$CONTAINER_NAME" \
--command "/bin/sh" \
--interactive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment