Search code examples
amazon-web-servicesaws-cdkaws-application-load-balancer

How do I enable deletion protection for load balancer using ApplicationLoadBalancedFargateService cdk construct


I have created a Fargate service running on an ECS cluster fronted by an application load balancer using the ApplicationLoadBalancedFargateService CDK construct.

  cluster,
  memoryLimitMiB: 1024,
  desiredCount: 1,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
});

There are no Props for enabling deletion protection. Can anyone tell from his experience?


Solution

  • CDK offers the Escape Hatches feature to use Clouformation Props if any High-level construct does not have parameters.

    import { CfnLoadBalancer } from "aws-cdk-lib/aws-elasticloadbalancingv2";
    
    // Create a load-balanced Fargate service and make it public
    var loadBalancedService =
      new ecs_patterns.ApplicationLoadBalancedFargateService(
        this,
        `MyService`,
        {
          cluster: cluster,
          taskImageOptions: {
            image: ecs.ContainerImage.fromRegistry("image"),
            environment: {},
          },
          assignPublicIp: true,
        },
      );
    
    // Get the CloudFormation resource
    const cfnLB = loadBalancedService.loadBalancer.node
      .defaultChild as CfnLoadBalancer;
    cfnLB.loadBalancerAttributes = [
      {
        key: "deletion_protection.enabled",
        value: "true",
      },