- Published on
ECS ExecuteCommand
Connecting to a running container on ECS (Fargate) can be very useful for monitoring or to debug issues you can't easily reproduce locally. In this post I'll shortly describe the process, assuming basic knowledge about the Elastic Container Service of AWS. I'll also assume that you already have an ECS Task that you would like to connect to ;)
Prerequisites
- Since this feature relies on the SSM (Systems Manager Session Manager) service to establish a session, you'll need to make sure that your ECS tasks can reach SSM, network-wise: either by adding a VPC inteface endpoint for it, or providing internet access to your services (NAT Gateway).
- You also need to have the Session Manager plugin for AWS Cli installed on your machine
Steps
- Add the necessary permissions to the ECS Task Role so that it can start a session.
You can create a new policy with these permissions, and attach it to the Task Role in question.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ssmmessages:CreateControlChannel",
"ssmmessages:CreateDataChannel",
"ssmmessages:OpenControlChannel",
"ssmmessages:OpenDataChannel"
],
"Resource": "*"
}
]
}
- Enable the ExecuteCommand feature for the service. For example via the CLI:
aws ecs update-service --region <region> --cluster <cluster> --service <service> --enable-execute-command
You can also redeploy your application, since this configuration change will only affect the tasks that are started after you made the change (running containers are not affected).
aws ecs update-service --cluster <cluster> --service <service> --enable-execute-command --force-new-deployment
- After the update (and deployment) is complete, you can run a command in a container.
For this you'll need the id of the task. If your task has multiple containers, the container name also has to be specified.
If you start a shell for example, your experience will be very similar to using docker exec -it ...
aws ecs execute-command --region <region> --cluster <cluster> --task <task_id> --container <container_name> --command "/bin/bash" --interactive
Note that after a period of inactivity your session might be terminated.
Cleanup
If you don't need the feature active anymore, you can disable it on the service (--disable-execute-command
) and remove the SSM policy from the Task Role.
You can find further details about this feature in the References