If you need to troubleshoot or debug your ECS Fargate containers, you may want to open a terminal on them. There are two options available to open a shell on an ECS container: with SSH or using the ECS CLI, a command-line tool provided by AWS. The first option may create potential drawbacks and security concerns: opening SSH port an managing private and public SSH keys. The second option doesn’t require you to enable SSH access or open any additional ports because it relies on IAM authentication and AWS Session Manager.
In my opinion, using the ECS CLI to access a terminal on ECS Fargate is generally more secure than enabling SSH access because the ECS CLI doesn’t require opening any additional ports or enabling direct access to your ECS containers, which can reduce the potential risk for security vulnerabilities.
In this article I will explain how to open a shell on an ECS container via the AWS CLI.
Install AWS CLI
Install AWS CLI depending on the architecture of your computer. For Linux x86 :
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
Install Session Manager Plugin
Install the Session Manager plugin for the AWS CLI. For Linux x86 :
curl "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/linux_64bit/session-manager-plugin.rpm" -o "session-manager-plugin.rpm"
sudo yum install -y session-manager-plugin.rpm
Attach the necessary IAM policy
Create an IAM policy ECSFargateAllowExecuteCommand and attach it to your ECS Task execution role :
{
"Statement": [
{
"Action": [
"ssmmessages:CreateControlChannel",
"ssmmessages:CreateDataChannel",
"ssmmessages:OpenControlChannel",
"ssmmessages:OpenDataChannel"
],
"Effect": "Allow",
"Resource": "*"
}
],
"Version": "2012-10-17"
}
Open a Shell
AWS CLI command ecs execute-command
requires 3 arguments :
- The ECS cluster name
- The ECS task id
- The container name
Open your ECS task on the ECS Console and retrieve the following information :
Use the information retrieved for the ECS CLI command :
aws ecs execute-command \
--region us-east-1 \
--cluster ECS_CLUSTER_NAME \
--task ECS_TASK_ID \
--container CONTAINER_NAME \
--command "/bin/bash" \
--interactive