Skip to content

Instantly share code, notes, and snippets.

@mowings
Last active February 27, 2024 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mowings/b7b7129d0dfd88cbbf5529ec052ee9ab to your computer and use it in GitHub Desktop.
Save mowings/b7b7129d0dfd88cbbf5529ec052ee9ab to your computer and use it in GitHub Desktop.
Run a shell in an ecs container via SSM

https://dev.to/aws-builders/how-to-run-a-shell-on-ecs-fargate-containers-eo1

Install session manager plugin locally

NOTE: It looks like the task default policy ALSO needs the ssm permissions as well. This CDK construct appears to copy those in; pulumi or other providers may not do the same.

Be sure that exec-command is set in the service definition. Via CDK:

const service = new ecs.FargateService(this, 'ecluster-service', {
      cluster,
      taskDefinition,
      enableExecuteCommand: true,
      }

Be sure the taskExecution policy in place allows ssm access:

// Create exec role and attach policy for ssm
    const execRole = new iam.Role(this, '${this.serviceName}-exec-role',{
      assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com')
    })
    // Create the IAM policy for the ECS execution role for ssm
    const ssmPolicy = new iam.Policy(this,'ssm-policy',{
      statements: [new iam.PolicyStatement({
        actions: [
          "ssmmessages:CreateControlChannel",
          "ssmmessages:CreateDataChannel",
          "ssmmessages:OpenControlChannel",
          "ssmmessages:OpenDataChannel",
          "logs:CreateLogStream",        
          "logs:PutLogEvents"
          // Anything else needed, ecr access, etc
        ],
        effect: iam.Effect.ALLOW,
        resources: ['*'],
      })],
    });
    execRole.attachInlinePolicy(ssmPolicy)
aws ecs execute-command  \
--cluster CLUSTER_NAME \
--task TASK_ARN \
--container CONTAINER_NAME \
--command /bin/bash \
--interactive

Port forward

Note that the ecs target id is in the format:

ecs:<cluster-name>_<task-id>_<container-runtime-id>

The latter is on the task detail page as a column in the container list.

aws ssm start-session --target ecs:testapp-test-Cluster-VHaYIQCdoUj8_c0add05ab98c49d798ba1cb515c9940d_c0add05ab98c49d798ba1cb515c9940d-527074092 \
  --document-name AWS-StartPortForwardingSession --parameters '{"portNumber":["8080"], "localPortNumber":["5000"]}'
$ curl localhost:5000
ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment