Borislav Hadzhiev
Reading timeยท2 min
Photo from Unsplash
Logical IDs serve as unique resource identifiers.
Logical IDs are alphanumeric (A-Za-z0-9) and must be unique in a template.
We set the resource's logical ID in CloudFormation like so:
Resources: # ๐ logical id MyLogicalId: Type: AWS::DynamoDB::Table Properties: # ... properties of the table
If we look at a deployed stack, we can see the Logical IDs of resources in the first column:
In order to override the Logical ID of a resource in CDK, we have to use the
overrideLogicalId
method on the CfnResource
.
To be more specific, if we had a CfnBucket resource we would use its overrideLogicalId method.
In order to demo the process, I'll create a CDK stack, which consists of a single S3 bucket:
import * as s3 from 'aws-cdk-lib/aws-s3'; import * as cdk from 'aws-cdk-lib'; export class MyCdkStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props: cdk.StackProps) { super(scope, id, props); const s3Bucket = new s3.Bucket(this, 'avatars-bucket', { removalPolicy: cdk.RemovalPolicy.DESTROY, }); // ๐ Get access to the CfnBucket resource const cfnBucket = s3Bucket.node.defaultChild as s3.CfnBucket; // ๐ Override the bucket's logical ID cfnBucket.overrideLogicalId('myLogicalId'); } }
In the code sample:
We defined an S3 bucket using the Level 2 Bucket construct.
We got access to the Level 1 CfnBucket
resource and casted the type of the
value to CfnBucket
.
We overrode the logical ID of the bucket to myLogicalId
my-logical-id
we would get an error: "Resource namemy-logical-id
is non alphanumeric."If we take a look at the synthesized CloudFormation template in the cdk.out
directory, we can see that the Logical ID we've provided is reflected in the
CloudFormation template:
Let's look at the Logical ID of the S3 bucket in the CloudFormation console:
We can see that the Logical ID of the bucket has been updated to the value we
provided - myLogicalId
.
If I were to change the logical ID of the bucket:
- cfnBucket.overrideLogicalId('myLogicalId'); + cfnBucket.overrideLogicalId('anotherLogicalId');
And now run the diff
command:
npx aws-cdk diff
The output shows that if I were to run a deployment, my bucket with logical ID
of myLogicalId
would get deleted and a new bucket with logical ID of
anotherLogicalId
would get created:
We should be mindful about identifiers in CDK, especially when working with stateful resources like S3 buckets and databases. I've written an article - What is an identifier in AWS CDK if you want to read more on the topic.