How to Connect to ECS Container

Connect to ECS Container

Avatar von Sven Pöche

In one of our projects, our developers needed to access an ECS container via shell for debugging purposes without requiring access to the underlying instances, SSH, jump/bastion hosts, or public addressing. Finally, we found the solution with ECS Exec.

Requirements

ECS Exec builds upon Session Manager, another AWS service that provides the same functionality for EC2 instances, so we need the Session Manager Plugin for our AWS CLI.

On macOS, you can use Homebrew to install both:

brew install awscli
brew install session-manager-plugin

For more installation options, see the appropriate tools pages.

Preparations

In our project, all permissions were already correctly configured. But in your project, granting permission for the ECS task to connect with the SSM Session Manager service might be necessary. You should add the following policy to your existing ECS task IAM role:

{
   "Version": "2023-03-03",
   "Statement": [
       {
       "Effect": "Allow",
       "Action": [
            "ssmmessages:CreateControlChannel",
            "ssmmessages:CreateDataChannel",
            "ssmmessages:OpenControlChannel",
            "ssmmessages:OpenDataChannel"
       ],
      "Resource": "*"
      }
   ]
}

In addition, your IAM role must have permission to execute ecs:ExecuteCommand. Add the following policy to your IAM role:

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

Last but not least, you must activate the ECS Exec feature in your existing task by using the parameter --enable-execute-command:

aws ecs update-service --cluster ${cluster-name} --service ${service-name} --enable-execute-command
aws ecs update-service --cluster staging-cluster --service staging-product-service --enable-execute-command

Connect to container

After everything is done, you can connect to the container with the following command:

aws ecs execute-command --cluster ${cluster-name} --task ${task-id} --container ${container-name} --interactive --command /bin/bash
aws ecs execute-command --cluster staging-cluster --task efbb9c1cfa5e353496345f78e3ba3962 --container staging-product-service --interactive --command /bin/bash

Further reading

If you are looking for information on actually debugging the containers, then I can recommend the following pages:

Avatar von Sven Pöche

Kommentare

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert


Für das Handling unseres Newsletters nutzen wir den Dienst HubSpot. Mehr Informationen, insbesondere auch zu Deinem Widerrufsrecht, kannst Du jederzeit unserer Datenschutzerklärung entnehmen.