Solve AWS CDK - Cannot use Tokens in Construct ID Error

avatar

Borislav Hadzhiev

Last updated: Apr 14, 2022

banner

Check out my new book

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`);

We 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 #

Use the search field on my Home Page to filter through my more than 3,000 articles.