Search code examples
amazon-web-servicesaws-cdknested-stack

Nested Stack can not be assigned a static name in aws cdk v2


since there is no way to give a static name for a Nested Stack, I tried this method in Nested Stack class (before the constructor)

getLogicalId(element: CfnElement): string {
        if (element.node.id.includes('NestedStackResource')) {
            return /([a-zA-Z0-9]+)\.NestedStackResource/.exec(element.node.id)![1] // will be the exact id of the stack
        }
        return super.getLogicalId(element)
    }

source: Source Link

Before trying this solution, it gave me nested stack name in CloudFormation as ; DevConnectBackendStack-DevConnectNestedStackDevConnectNestedStackResourceAB8916B0-IBLMSGR9L2IO

After trying above method in my nested stack I got the nested stack name as ;

DevConnectBackendStack-NestedLambdaCommonStackNestedStackNestedLambdaCommonStackNested-1X8VVCE0WRW10

But I prefer to have DevConnectBackendStack-NestedLambdaCommonStack-1X8VVCE0WRW10. why it is not possible to have this kind of a stack name ?

my-nested-stack.ts

export class NestedLambdaCommonStack extends cdk.NestedStack {

  getLogicalId(element: CfnElement): string {
        if (element.node.id.includes('NestedStackResource')) {
            return /([a-zA-Z0-9]+)\.NestedStackResource/.exec(element.node.id)![1] 
        }
        return super.getLogicalId(element)
    }
     constructor(scope: Construct, id: string, props: NestedLambdaCommonStackProps){}

}

nested stack on parent stack;

const nestedLambdaCommonStack = new NestedLambdaCommonStack(this, 'NestedLambdaCommonStack', {})

Solution

  • The Nested stack provisions resources written in Nested stack only. The Nested stacks are created by Main stack. Therefore, The Nested stack names can be overridden in Main stack only. Put below method in Main stack and it worked.

    getLogicalId(element: CfnElement): string {
            if (element.node.id.includes('NestedStackResource')) {
                return /([a-zA-Z0-9]+)\.NestedStackResource/.exec(element.node.id)![1] 
            }
            return super.getLogicalId(element)
        }