When running docker, whether locally or on a virtual machine, it’s pretty easy to access the command line for your container with docker exec, assuming you have access to the command line of the host where the Docker daemon is running.
However when managing containers on Elastic Container Services (ECS), this approach falls short - particularly when using Fargate. Fargate is the “serverless” option for ECS, meaning there’s no underlying host machine to access. Traditional SSH methods won’t work here.
Session Manager to the rescue
AWS Systems Manager Session Manager is a managed service to connect to compute resources, for example EC2, without SSH and keys. You may well have even used it without realising if you ever clicked “connect” from the browser EC2 control plane to access an instance.
Enable it on your ECS Service: The ECS Service has a configuration option EnableExecuteCommand - if set to true this is enabled for all containers in the service.
Networking: Your target container must be running in a VPC that has either an SSM Endpoint or configured NAT Gateway.
The AWS Docs have some great further examples, for example denying access to a production machine.
Encryption By default, the data transferred between your local client and the container uses TLS 1.2 encryption that AWS provides. You can also specify your own keys of course, more on that here
Using ECS Exec
Assuming you’ve succesfully followed the above, you have valid CLI credentials, then all that remains is to execute the aws ecs execute-command command and enter your container!
Unfortunately, it’s a little unwiedly, the command looks a little like this:
Broken down, you need your clusterName, TaskName, TaskID, region, and then the approprate shell (bin/bash, bin/sh) depending on how the image is built.
The clusterName and containerName are specified when setting it up, to access the task ID you can either use the browser console, or the cli, perhaps ecs list-tasks to retreive a list of task ARNs
giving something like arn:aws:ecs:REGION:ACCOUNTID:task/myClusterName/myTaskId1 arn:aws:ecs:REGION:ACCOUNTID:task/myClusterName/myTaskId2
Conclusion
ECS Exec from SessionManager dramatically simplifies and secures accessing ECS containers running on either EC2 or Fargate - infact, for Fargate it is the only option.
Note: Frequent SSH access into containers might indicate a need to improve your application design or consider alternative debugging techniques.
No comments yet. Be the first to comment!