Solving Resource name is non alphanumeric Error in AWS CDK

avatar

Borislav Hadzhiev

Last updated: Apr 14, 2022

banner

Check out my new book

Resource name is non alphanumeric Error #

Resource names, also known as Logical IDs are resource identifiers in CloudFormation and we set them like so:

Resources: # 👇 logical id MyLogicalId: Type: AWS::S3::Bucket Properties: # ... properties of the bucket

Logical IDs are only allowed to contain alphanumeric [A-Za-z0-9] characters.

However, when using CDK, logical IDs are created for us automatically.

The reason we get the Resource name is non alphanumeric Error in CDK is, because we're setting the Logical ID of a resource to contain non-alphanumeric characters.

For example, I'll define an S3 bucket and override it's logical ID to contain non alphanumeric characters:

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, }); const cfnBucket = s3Bucket.node.defaultChild as s3.CfnBucket; // 👇 Non alphanumeric cfnBucket.overrideLogicalId('my-logical-id'); } }

In the code snippet, we have overridden the logical ID of an S3 bucket, however we've used dashes. Since dashes are non alphanumeric characters, we will get an error if we try to deploy.

I'll now try to deploy the CDK stack:

shell
npx aws-cdk deploy

The output shows that we get a ValidationError:

non alphanumeric error

In order to solve the Resource name is non alphanumeric error in CDK,we have to only provide alphanumeric characters when overriding Logical IDs via the overrideLogicalId function:

const s3Bucket = new s3.Bucket(this, 'avatars-bucket', { removalPolicy: cdk.RemovalPolicy.DESTROY, }); const cfnBucket = s3Bucket.node.defaultChild as s3.CfnBucket; // 👇 Only contains alphanumeric characters cfnBucket.overrideLogicalId('myLogicalId');

If you want to read more on identifiers in CDK, I've written an article - What is an identifier in AWS CDK.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.