Solve AWS CDK - Cannot use Tokens in Construct ID Error

avatar

Borislav Hadzhiev

Fri Apr 30 20212 min read

banner

Photo by Brooke Cagle

Solving Cannot use Tokens in Construct ID Error in CDK #

Tokens in CDK are encoded values, most commonly attributes of a resource, that get resolved by CloudFormation at deployment time.

For example trying to access the bucketName of an s3 bucket at synthesis time returns a token.

const bucket1 = new s3.Bucket(this, 'bucket-1'); console.log('bucket name ๐Ÿ‘‰', bucket1.bucketName);

bucket name token

We can't access the resolved value of a CDK token in our code, i.e. in conditional statements or when trying to assign a construct id.

The following code gets the "Cannot use Tokens in Construct ID" Error:

const bucket1 = new s3.Bucket(this, 'bucket-1'); const bucket2 = new s3.Bucket(this, `${bucket1.bucketName}-2`);
In order to solve the "Cannot use Tokens in Construct ID" error, we have to remove the token from the construct id.
const bucket1 = new s3.Bucket(this, 'bucket-1'); const bucket2 = new s3.Bucket(this, `${bucket1.node.id}-2`);

In the code snippet we've used the id of the bucket1 resource within the current scope to create the id of the bucket2 resource.

In this case, the id of the bucket2 resource is going to be bucket-1-2.

Alternatively, you could use the addr property:

const bucket1 = new s3.Bucket(this, 'bucket-1'); const bucket2 = new s3.Bucket(this, `${bucket1.node.addr}-2`);

The addr property returns a 42 char hexadecimal string based on the construct's path.

Further Reading #

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee