amazon-web-servicesgoamazon-ecsaws-cdkecs-taskdefinition

AWS CDK ECS Task Definition Without Task Role


In AWS CDK v2 the ECS TaskDefinition L2 construct has an optional property TaskRole if not specified CDK default behavior is to create a task role. However I do not want a task role set for this resource, it is not actually required in AWS - the Task Definition can function without this property. How can i manage that in CDK? I can't see any way to unset that task role or not have it generated in the first place. Do I need to step back to the L1 construct for this? My configuration:

taskDefinition := awsecs.NewEc2TaskDefinition(stack, jsii.String(deploymentEnv+service.Tag+"TaskDef"), &awsecs.Ec2TaskDefinitionProps{
            Family:      jsii.String(deploymentEnv + service.Tag), 
            NetworkMode: awsecs.NetworkMode_BRIDGE,
            //TaskRole: what can i do here to fix this
            Volumes: &[]*awsecs.Volume{
                &efs_shared_volume,
            },
        })

Solution

  • You can remove arbitrary child constructs by ID, using the tryRemoveChild escape hatch method:

    // remove the role
    taskDefinition.Node().TryRemoveChild(jsii.String("TaskRole"))
    
    // remove the reference to the role
    t := taskDefinition.Node().DefaultChild().(awsecs.CfnTaskDefinition)
    t.AddPropertyDeletionOverride(jsii.String("TaskRoleArn"))
    

    The trick is identifying the construct ID. You sometimes need to look for it in the source code.