'AWS CDK: fixed logical ids

Currently logical ID of a resource is formed by concatenating the names of all of the constructs in the resource’s path and appending an eight-character MD5 hash.

This produces garbage like VpcPrivateSubnet1DefaultRouteBE02A9ED and unfortunatelly makes it unable to query the resources by their logical id.

Is there any way to control how logical ids are named?



Solution 1:[1]

In TypeScript the method you are looking for is overrideLogicalId. But you have to get the lower level CfnVpc construct first by using the following code (TypeScript again):

 let vpc = new ec2.Vpc(this, 'vpc', { natGateways: 1 })
 let cfnVpc = vpc.node.defaultChild as ec2.CfnVPC
 cfnVpc.overrideLogicalId('MainVpc')

Results in the following yaml:

  MainVpc:
    Type: AWS::EC2::VPC

Solution 2:[2]

A bit late to the party but here is my implementation. I removed the random characters at the end of the string and replaced it with the logical ID which are unique throughout the project.

protected allocateLogicalId(cfnElement: CfnElement): string {
  return cfnElement.logicalId.split('.')[1];
}

Solution 3:[3]

For anyone looking for a solution in Python:

from aws_cdk import aws_lambda as lambda_

api_function = lambda_.Function(
    self,
    "lambda_func",
    code=lambda_.Code.from_bucket(bucket=s3_bucket, key='lambda.zip'),
    runtime=typing.cast(lambda_.Runtime, lambda_.Runtime.PYTHON_3_9), # Bug in CDK/PyLance; use cast to mitigate for now
    timeout=Duration.seconds(900),
    handler="rest_client.handler"
    )

cfn_func = api_function.node.default_child
cfn_func.override_logical_id("NewLogicalId")

(Note: PyLance throws the following error, but cdk ls and cdk synth work as expected:

override_logical_id: Unknown
Cannot access member "override_logical_id" for type "IConstruct"
  Member "override_logical_id" is unknownPylancereportGeneralTypeIssues
"override_logical_id" is not a known member of "None"

Please note: It is generally not recommended to change logical IDs as changing the logical ID of a resource causes the resource to be replaced. The old resource will get deleted, and a new resource with the new logical ID gets created.

From the docs:

Avoid changing the logical ID of a resource after it has been created. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID, which may cause service interruption or data loss.

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 quadroid
Solution 2 Victor Coelho De Oliveira
Solution 3