Skip to main content

Access ECS Container Terminal

This guide provides step-by-step instructions on how to install necessary plugins, configure permissions, and enable the AWS ECS execute command feature for interactive task management. This feature allows you to interact with your containers without the need to open inbound ports, manage SSH keys, or use bastion hosts.

Prerequisites

  • AWS CLI installed and configured
  • jq installed (for parsing JSON in bash scripts)
  • AWS IAM permissions to modify ECS services and tasks
  • Homebrew installed (for macOS users)

Installation

Install Session Manager Plugin

The Session Manager plugin is required for the AWS CLI to start a session with your containers. Install it using Homebrew:

brew install --cask session-manager-plugin

Configuration

IAM Permissions

Task Role

Add the following permissions to the task role to allow tasks to communicate with the Systems Manager service endpoints:

{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"ssmmessages:CreateControlChannel",
"ssmmessages:CreateDataChannel",
"ssmmessages:OpenControlChannel",
"ssmmessages:OpenDataChannel"
],
"Effect": "Allow",
"Resource": "*",
"Sid": "AllowTaskTerminalAccess"
}
]
}

User/Role

Ensure the user or role executing these commands has the following permission to use ECS ExecuteCommand:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "User access to ECS ExecuteCommand",
"Effect": "Allow",
"Action": "ecs:ExecuteCommand",
"Resource": "*"
}
]
}

Enabling Execute Command

tip

For those utilizing Terraform, our Optimus Terraform AWS ECS Service module simplifies enabling the execute command feature on your ECS services. It's designed to integrate seamlessly into your infrastructure, ensuring best practices and efficiency. Consider leveraging this module to enhance your ECS service setup with minimal effort.

Use AWS CLI to enable the execute command feature for your service. Here's how to do it with the AWS CLI:

aws ecs update-service \
--cluster <cluster-name> \
--task-definition <task-definition-name> \
--service <service-name> \
--enable-execute-command

Connect to ECS Container

To execute commands within a container of a specific task, follow these steps:

1. Set Environment Variables

Set the necessary variables for your region, cluster name, service name, and container name:

REGION="ap-southeast-1"
CLUSTER_NAME="your-cluster-name"
SERVICE_NAME="your-service-name"
CONTAINER_NAME="your-container-name"

2. List Tasks and Extract Task ID

Use the AWS CLI to list tasks for the service and extract the first task ID:

TASK_ID=$(aws ecs list-tasks \
--region $REGION \
--cluster $CLUSTER_NAME \
--service-name $SERVICE_NAME \
--query "taskArns[]" \
--output json | jq -r '.[0]' | awk -F'/' '{print $NF}')

3. Connect

You can try /bin/sh or /bin/bash

aws ecs execute-command \
--region $REGION \
--cluster $CLUSTER_NAME \
--task $TASK_ID \
--container $CONTAINER_NAME \
--command "/bin/sh" \
--interactive