Skip to content
Quest 06Intermediate14 min

Tokens and Outputs

You have already used a token without naming it: table.tableName. Tokens are the idea that makes CDK feel odd for a day and obvious forever after, and stack outputs are how you show the real values to people.

What you'll learn

  • A token stands for a value that CloudFormation only knows at deploy time: a generated name, an ARN, an endpoint URL.
  • You can put tokens in strings (template literals and f-strings). CDK turns the result into Fn::Join.
  • Don't compare or branch on a token's value, and don't print it expecting the real name. Pass it onward, or export it with a CfnOutput.

Section 01

What a token is

While your program runs, there is no bucket yet, so there is no bucket name. bucket.bucketName returns a string that looks like ${Token[TOKEN.123]}: a marker. When CDK writes the template, it replaces the marker with the reference that CloudFormation understands: { "Ref": "CardsBucket685ECB20" }.

Tokens inside a string
const prefix = `s3://${bucket.bucketName}/cards/`;
// synthesizes to: { "Fn::Join": ["", ["s3://", { "Ref": "CardsBucket…" }, "/cards/"]] }

Section 02

Ref, GetAtt and Join

Three CloudFormation functions carry nearly every token:

FunctionWhat it returnsExample token
RefThe resource's main identifier (often the name)bucket.bucketName
Fn::GetAttAnother attribute, such as the ARNtable.tableArn
Fn::JoinSeveral pieces glued into a stringAny string that contains a token

Section 03

Stack outputs

A CfnOutput publishes a value after a deploy: it appears in the CLI, in the console, and can be exported for other stacks. Use outputs for what people and pipelines need: an API URL, a bucket name, a table ARN.

In the exercise you also fix CARD_PREFIX, which guesses the bucket name. The starter's message explains why the guess would fail only after deploy, which is the worst time to find out.

Export the real values
new cdk.CfnOutput(this, "CardsBucketName", { value: bucket.bucketName });
new cdk.CfnOutput(this, "PokedexTableArn", { value: table.tableArn });

Practice

Your turn

CARD_PREFIX is a hard-coded guess at the bucket name. Build it from bucket.bucketName so it becomes s3://<real bucket name>/cards/. Then export two stack outputs: CardsBucketName (the bucket name) and PokedexTableArn (the table ARN).

CARD_PREFIX built from the bucket-name token, plus CfnOutputs CardsBucketName and PokedexTableArn.
Tab inserts two spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the code.
Simulated — no AWS calls

The simulator runs the constructs this course teaches, plus simple loops and helper methods. Other CDK code may not be recognised.

Check

Check your understanding

Quick Quiz · one question, as many tries as you need.

Your code reads bucket.bucketName and logs it during cdk synth. What do you see?

Choose one answer.