Home > Net >  AWS CDK ECS Task Definition Without Task Role
AWS CDK ECS Task Definition Without Task Role

Time:01-18

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,
            },
        })

CodePudding user response:

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

taskDefinition.Node().TryRemoveChild(jsii.String("TaskRole"))

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

CodePudding user response:

In the CDK, it's necessary because the L2 construct implements the Grantable interface, and its methods depend on the existence of the role. Technically, you can override almost any property on any node which would allow you to get this effect, but that may result in difficult to track errors down the road.

Additionally, if no role is specified for a task definition, your tasks inherit permissions from the EC2 instance role in the cluster, which is almost certainly not a behavior you want. If that is the behavior you want, you're better off explicitly defining the role to be the same as the role used in the EC2 cluster.

Alternatively, if your intention is to make your tasks have no permissions, your best bet is to either stick with the default behavior or explicitly define a role with no attached policies then (optionally) pass the object returned by the .withoutPolicyUpdates on the role object to prevent it from being updated by grants.

const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'),
  description: 'Empty ECS task role with no permissions',
});

// ...

taskDefinition := awsecs.NewEc2TaskDefinition(stack, jsii.String(deploymentEnv service.Tag "TaskDef"), &awsecs.Ec2TaskDefinitionProps{
            // ...
            TaskRole: role.withoutPolicyUpdates(),
            // ...
            },
        })
  • Related