How to fix unable to update task definition on services with a CODE_DEPLOY deployment controller CDK issue

How to fix unable to update task definition on services with a CODE_DEPLOY deployment controller CDK issue

ยท

2 min read

AWS CDK rolled out a change in their version 2.50.0 as per this GitHub discussion which caused a dependency on the task definition family for ECS services instead of referencing the task definition revision. This caused deployment issues for users trying to upgrade CDK version to v2.50.0 or above.

Why does it happen?

The issue is caused by the following dependency in the aws-cdk-lib package:

if (props.deploymentController?.type === DeploymentControllerType.CODE_DEPLOY) { 
   // Strip the revision ID from the service's task definition property to 
   // prevent new task def revisions in the stack from triggering updates 
   // to the stack's ECS service resource 
   this.resource.taskDefinition = taskDefinition.family; 
   this.node.addDependency(taskDefinition); 
 }

Solution

Let's say your CDK code for creating ECS service looks like this:

    ...
    // Task definition
    const taskDef = new ecs.FargateTaskDefinition(this, "ecstaskdefinition", {
      taskRole: taskRole,
      family: `myapplication`
    });

    // dummy container for initializing
    const initContainerRepo = ecr.Repository.fromRepositoryName(this, 'Repo', "init-container");
    const container = taskDef.addContainer(`myapplication`, {
      image: ecs.ContainerImage.fromEcrRepository(initContainerRepo), // fromRegistry("amazon/amazon-ecs-sample"),
      memoryLimitMiB: 256,
      cpu: 256,
      logging
    });

    container.addPortMappings({
      containerPort: 80,
      protocol: ecs.Protocol.TCP
    });

    // ECS service
    const service = new ecs.FargateService(this, 'FargateService', {
      cluster,
      taskDefinition: taskDef,
      serviceName: `ecs-myapplication-01`,
      healthCheckGracePeriod: cdk.Duration.seconds(60),
      desiredCount: desiredCount,
      deploymentController: {
        type: ecs.DeploymentControllerType.CODE_DEPLOY
      },
    });
...

The dependency issue between ECS service and Task definition family can be resolved by adding the following code below ECS service:

    // Override the dependency on Task definition family
    const cfnService = service.node.defaultChild as ecs.CfnService;
    cfnService.addOverride('Properties.TaskDefinition', service.taskDefinition.taskDefinitionArn);

This override will remove the dependency and allow you to complete the deployment.

Feel free to reach out if you face any issues!
Follow me for more cloud and DevOps content.
See you in cloud!
Vishnu S.

Did you find this article valuable?

Support Learn More Cloud by becoming a sponsor. Any amount is appreciated!

ย