Enable ExecuteCommand on AWS Fargate via cdk in a ApplicationLoadBalancedFargateService

Viewed 1176

Currently have configured AWS Fargate service with ApplicationLoadBalancedFargateService via AWS CDK(Python), would like to enable ExecuteCommand on the fargate containers to get access over them.

But currently unable to find a method to enable Exec on this fargate service.

Any help on this would be much appreciated.

3 Answers

In case anyone needs the command to enable shell access from the cli.

aws ecs update-service --cluster <cluster_name> --service <service_name> --task-definition <task_definition_name> --enable-execute-command --force-new-deployment

On a bit of a side note: You will also need to create a custom AWS Service: ecs-tasks role that includes Systems Manager permissions in addition to the AmazonECSTaskExecutionRolePolicy that comes in the default ecs-tasks role ecsTaskExecutionRole.

Here's an example policy.

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "VisualEditor0",
        "Effect": "Allow",
        "Action": [
            "ssmmessages:CreateDataChannel",
            "ssmmessages:OpenDataChannel",
            "ssmmessages:OpenControlChannel",
            "ssmmessages:CreateControlChannel"
        ],
        "Resource": "*"
    }
]
}

One can now enable execute command via CDK:

declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  desiredCount: 1,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  enableExecuteCommand: true
});

Source: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs_patterns-readme.html#ecs-exec

There seem to be an open issue/feature request in the aws-cdk repo that describes your issue.

The workaround is using Escape Hatches:

cfn_service = self.web_service.service.node.default_child
cfn_service.add_override("Properties.EnableExecuteCommand", True)

From my experience I learned that the ApplicationLoadBalancedFargateService is still limited. In some cases it makes sense to use the FargateService and create the loadbalancer, portmappings,... yourself.

Related