Sub topic 8
Tokens: values that exist only at deploy time
This chapter assumes you can define a stack with a bucket and a Lambda function, as in the earlier chapters. You should also know that cdk synth produces a CloudFormation template and that cdk deploy sends it to AWS.
The problem tokens solve
Some values cannot be known when your CDK code runs. A bucket's name, if you did not set one, is generated by CloudFormation during deployment. A Lambda function's ARN depends on the account and region it lands in. Your code still needs to pass these values around, for example to put the bucket name in a function's environment variables.
The CDK handles this with tokens. A token is a placeholder that stands in for a value that will be resolved later. When you read bucket.bucketName, you do not get a real name. You get a string that encodes a reference to the bucket. During synthesis the CDK replaces that placeholder with the right CloudFormation expression, such as { "Ref": "UploadsBucket..." }.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
export class TokenDemoStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const bucket = new s3.Bucket(this, 'DemoBucket');
console.log(bucket.bucketName);
console.log(cdk.Token.isUnresolved(bucket.bucketName));
}
}
const app = new cdk.App();
new TokenDemoStack(app, 'TokenDemoStack');Running cdk synth on this prints something like ${Token[TOKEN.123]} followed by true. The first line is the encoded placeholder. The second confirms that the value is unresolved.
How the CDK resolves tokens
Resolution happens in the final phase of synthesis. The CDK walks the construct tree, finds every token embedded in the resource properties, and replaces each one with its CloudFormation form.
| Token source | Resolved to in the template |
|---|---|
| `bucket.bucketName` | `{ "Ref": "..." }` |
| `bucket.bucketArn` | `{ "Fn::GetAtt": ["...", "Arn"] }` |
| `cdk.Aws.REGION` or `stack.region` (when no environment is set) | `{ "Ref": "AWS::Region" }` |
| `cdk.Fn.join(...)` with token parts | `{ "Fn::Join": [...] }` |
CloudFormation then evaluates these expressions during deployment, when the real values exist.
Tokens are strings, numbers and lists
Tokens can be encoded as strings, numbers, or string lists, so they fit into properties of those types. This is why environment: { BUCKET_NAME: bucket.bucketName } type-checks and works.
Numbers are encoded as unusual floating-point values, and list tokens are encoded as a list containing a single special string. This has consequences for what you can do with them.
What you cannot do with a token
Because a token is a placeholder, any code that needs the real value at synthesis time will misbehave.
- Do not compare it:
if (bucket.bucketName === 'my-bucket')is always false. - Do not parse it:
bucket.bucketName.split('-')operates on the placeholder text, not the name. - Do not do arithmetic on a number token, or check the length of a list token.
- Do not use it as a construct ID. IDs must be known during synthesis, because they decide the logical IDs of your resources.
If you need to know whether a value is a token, use cdk.Token.isUnresolved(value). This is useful in code that accepts user input and validates it only when the value is concrete.
Working with tokens correctly
When you need to build a string from token parts, use string interpolation or the helpers in Fn. Interpolation works because the placeholder is just text, and the CDK resolves each embedded token.
from aws_cdk import App, Fn, Stack
from aws_cdk import aws_s3 as s3
from constructs import Construct
class JoinDemoStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
bucket = s3.Bucket(self, "DemoBucket")
by_interpolation = f"s3://{bucket.bucket_name}/reports/"
by_fn_join = Fn.join("", ["s3://", bucket.bucket_name, "/reports/"])
print(by_interpolation)
print(by_fn_join)
app = App()
JoinDemoStack(app, "JoinDemoStack")
app.synth()Both strings produce an Fn::Join in the template. You can read the printed output as placeholders, but the template contains correct expressions.
To look at a resolved value in a test or a script, use stack.resolve(value). It returns the CloudFormation JSON that the token will become.
const resolved = cdk.Stack.of(this).resolve(bucket.bucketName);
console.log(JSON.stringify(resolved));For a bucket, this prints a Ref object, which shows exactly what CloudFormation will receive.
Tokens and environments
The earlier chapter on environments showed that a stack can be environment-agnostic or tied to an account and region. This affects tokens directly.
- If you set
envwith concrete values,stack.regionandstack.accountare plain strings. You can compare and parse them. - If you leave
envunset, those properties are tokens that resolve toAWS::RegionandAWS::AccountId. You cannot branch on them in code.
This is a frequent source of confusion. A condition such as if (stack.region === 'us-east-1') silently fails in an environment-agnostic stack, because the left side is a token. If your logic depends on the region, set env explicitly.
Tokens across stacks
When a value from one stack is used in another, the CDK turns the token into a CloudFormation export and import automatically, or into a parameter reference, depending on how you wire the stacks. The mechanics are covered in the chapter on sharing values across stacks. What matters here is the reason it works: the token carries a reference, so the CDK knows which resource the value came from and can create the dependency.
Common errors
- Using a token as an ID. The CDK throws an error that a construct ID or name contains an unresolved token. Use a fixed string for IDs.
- Branching on a token. The branch you expect never runs. Use CloudFormation conditions (
CfnCondition) when the decision must happen at deploy time. - Parsing a token. String methods act on the placeholder. Use
Fn.select,Fn.splitorFn.joinso CloudFormation does the work. - Validating a token. Length or pattern checks on a token value fail or pass incorrectly. Guard them with
Token.isUnresolved. - Printing a value to debug. Logging shows placeholders. Check
cdk.out/*.template.jsonor callresolve.
Summary of the model
Your code runs once, on your machine, during cdk synth. CloudFormation runs later, in AWS. Tokens are the bridge between the two. Anything the CDK can compute during synthesis is a normal value. Anything only AWS can supply is a token, and you may pass it along but not inspect it.
Exercise
A stack has no env set. A teammate writes if (this.region === 'eu-west-1') { fn.addEnvironment('EU', 'true'); } and finds the variable is never added, even when deploying to eu-west-1. Why does this happen, and what are two ways to fix it?
Show answer
Without env, this.region is a token that resolves to AWS::Region at deploy time. At synthesis it is a placeholder string, so the comparison with 'eu-west-1' is always false. Fix it by setting env with a concrete account and region so this.region is a plain string, or by using a CloudFormation condition (CfnCondition with Fn.conditionEquals(cdk.Aws.REGION, 'eu-west-1')) so the decision happens at deploy time.
Exercise
Which of these is safe with bucket.bucketName: using it as an environment variable value, passing it to .toUpperCase(), or using it inside a template string such as ` s3://${bucket.bucketName}/ `? Explain each.
Show answer
Using it as an environment variable value is safe, because the CDK resolves the token to a Ref. The template string is also safe, because the placeholder is embedded in the string and resolved to an Fn::Join. Calling .toUpperCase() is not safe, because it changes the placeholder text itself, which breaks the token and produces garbage instead of the uppercased bucket name.