'Prefix automatically created roles using AWS CDK

I need to be able to prefix any roles that are automatically created when deploying a stack and I am having trouble finding where and how to do this?

So when the iam:CreateRole is called on something like arn:aws:iam::***:role/cdk-hnb659fds-cfn-exec-role-***-region I would like it to be arn:aws:iam::***:role/{$customPrefix}-cdk-hnb659fds-cfn-exec-role-***-region.

I tried to override the allocateLogicalId in my stack:

 public allocateLogicalId(element: CfnElement) {
    const orig = super.allocateLogicalId(element);
    const prefix = "custom-";
    return prefix ? prefix + orig : orig;
  }

But if I want to add a - it complains about Error: Resolution error: Resolution error: Resolution error: Resolution error: Logical ID must adhere to the regular expression: /^[A-Za-z][A-Za-z0-9]{1,254}$/, got 'custom-AppSyncAPIApiB9F19C81'..

if I don't add a dash it works. But it also prefixes everything in my stack. I would like to only prefix the IAM roles that are being created.

Is there any way to do this?



Solution 1:[1]

cdk bootstrap deploys a CloudFormation template. The template defines the bootstrapping roles' Physical IDs (= names) using substitution patterns:

# bootstrap-template.yaml
RoleName:
  Fn::Sub: cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}

Bootstrap the environment with a custom template, in which you modify the role names:

# print the default template to the console
cdk bootstrap --show-template

# bootstrap with a custom template
cdk bootstrap --template my-bootstrap-template.yaml

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fedonev