2-Minute Guide to Access containers on AWS Fargate under AWS ECS
Given the occupational hazard of being constantly paranoid and pessimistic, which software engineer wouldn’t want to gain access to their deployed containers on the Cloud just to check things are going well from time to time. Fortunately, AWS ECS recently launched official support to gain interactive access to deployed containers, which was difficult to achieve before, especially if you were using Fargate.
The official announcement shared a very comprehensive guide on gaining access. I managed to access my containers on Fargate together with a few StackOverflow and Github issue comments. However, comprehensive is a decent word for long and time-consuming and we software engineers are very impatient people. So to save the effort for future fellow engineers who want to gain access to their containers on Fargate, I have summarized a gist in this article.
Setup Installation
- AWS CLI (the version that worked for me was 2.2.14)
- SSM Session Manage Plugin for AWS CLI
Enable Execute Command
In order to gain access to the containers, it’s necessary to enable execute command. To check whether it’s already enabled, run the following in the command line:
# make sure you are in the right region to view your AWS services
# get the cluster name
aws ecs list-clusters# get the task name
aws ecs list-tasks --cluster <cluster_name># describe the task to check enableExecuteCommand
aws ecs describe-tasks --tasks <task_id> --cluster <cluster_name>
If you run into authentication issues with AWS CLI, check this guide.
If the execute command is not already enabled, you can either enable it during run-task or update your service definition to always enable execute command by default. I will show the example to update the existing service.
# get the service name
aws ecs list-services --cluster <cluster_name># update existing service to enable execute command
aws ecs update-service --service <service_name> --cluster <cluster_name> --enable-execute-command
Attach SSM Policy to the Task Role
Be careful, there are two roles used to launch a task: the Execution Role and the Task Role. We want to attach the AmazonSSMFullAccess to the Task Role, not the Execution Role.
One LAST Step
Getting in.
# get container name
aws ecs describe-tasks --tasks <task_id> --cluster <cluster_name># create interactive cli access
aws ecs execute-command \
--region <aws_region> \
--cluster <cluster_name> \
--task <task_id> \
--container <container_name> \
--command "/bin/sh" \
--interactive
If everything goes well, you should see the following and you are in. Voilà.
The Session Manager plugin was installed successfully. Use the AWS CLI to start a session.Starting session with SessionId: XXXXXXXXXXXXXXXXXXXXXXXXXXX
Happy Coding!