Mike P.
Mike P.

Reputation: 198

AWS CDK - How to use "placeholder" token with Low Level cfn constructs

I am using CDK (in typescript) to define an AWS Timestream DB and a table inside it.

I want to allow AWS to set the name of the database (and avoid hardcoding it). The problem is how to reference that database name in the table construct.

CDK users' will know that the actual database name is not defined until it is created in AWS (which is after the CDK code that defines the table is executed). For this purpose, CDK created the idea of a placeholder Token (my emphasis).

I know that in the higher level CDK constructs, the placeholder Token is already defined. This doesn't seem to be the case for low level cfn constructs.

Here is some sample code to explain:

This code uses the higher level dynamo construct and lambda and works:

const table = new dynamodb.Table(this, id);
const lambda = new lambda.Function(this, id);
lambda.addEnvironment("TABLE_NAME", table.tableName)
console.log(`table Token is: ${table.tableName}`); // prints *like* "${Token[TOKEN.540]}"

This is the code I am writing for AWS Timestream and no token is generated:

const db = new ts.CfnDatabase(this, id);
console.log(`database name is is: ${db.databaseName}`); // prints null
const table = new ts.CfnTable(this, id, { 
  databaseName: db.databaseName,
  });// this will break as databaseName is null

My questions:

  1. Why: why doesn't the lower level construct generate the Token.
  2. How: I think I can create a token and assign it to db.databaseName but I have no clue how to populate that Token with data when the cdk deploy is run.

Any help on sample code to generate the Token and populate it would be greatly appreciated.

Upvotes: 2

Views: 1702

Answers (1)

Elad Ben-Israel
Elad Ben-Israel

Reputation: 844

You are probably looking for ref instead of databaseName:

const db = new ts.CfnDatabase(this, id);
console.log(`database name is is: ${db.ref}`); // prints null

const table = new ts.CfnTable(this, id, { 
  databaseName: db.ref,
});

This corresponds 1:1 to the AWS::Timestream::Database CloudFormation resource. As the docs describe, the Ref return value represents the database name.

Background: properties exposed in "CFN resources" (also known as L1 resources), include both the resource properties (as they are configured when the object is initialized) and resource attributes, which is what you are after.

Upvotes: 3

Related Questions