amazon-web-servicesamazon-iamaws-cdk

Set the name of an automatically created Role in the CDK


For example, when making a task definition:

const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDefinition', {
  networkMode: ecs.NetworkMode.AWS_VPC,
})

This makes the role automatically, and named automatically.

From the document, there is property to set the role, but it accepts IRole not name.

Is there any method to name the role which is automatically created?

Alternatively, I suppose I should use class Role to make role in advance and attache this to the Ec2TaskDefinition?, however how can I know the role property?


Solution

  • An ECS TaskDefinition has two role props, the executionRole and the taskRole.1 If you pass a role construct to these props, you can set the role name directly. If you don't set the props, you can use escape hatch syntax to modify the name of the automatically created default roles:

    if (!taskDefinition.taskRole) {
        throw new Error("The Task Role is undefined");
    }
    
    const cfnTaskRole = taskDefinition.taskRole.node.defaultChild as iam.CfnRole;
    
    cfnTaskRole.addPropertyOverride("RoleName", "my-task-role");
    

    [1] See Difference between AWS Elastic Container Service's (ECS) ExecutionRole and TaskRole