Tokens
Tokens represent values that are unknown until Terraform applies your configuration. For example, names of cloud resources are only assigned upon creation.
Some attributes specified using CDK for Terraform (CDKTF) may not directly map to the values required for Terraform configurations. You can use Tokens to cast these attributes to the correct Terraform language syntax.
Use Tokens
You may need to use Tokens for:
- Module outputs for boolean, string, lists, maps, and other complex types.
- Resource attributes (such as
id
). - Terraform outputs based on resource attributes.
- Using Terraforms
null
type.
Example
An EKS module requires a list of subnet ids in order to create a cluster. The VPC module outputs a list of subnets.
To pass the subnet id list to the EKS module, you can use publicSubnetsOutput
to retrieve the list from the VPC. However, the subnets
attribute
requires a list of strings. Use Token.asList(vpc.publicSubnetsOutput)
to cast the interpolated module
output as a list of strings.
import { TerraformStack, TerraformVariable, Token } from "cdktf";import { Construct } from "constructs";import { Vpc } from "./.gen/modules/terraform-aws-modules/aws/vpc";import { Eks } from "./.gen/modules/terraform-aws-modules/aws/eks"; export class TokensStack extends TerraformStack { constructor(scope: Construct, id: string, vpcName: string) { super(scope, id); const logRetention = new TerraformVariable(this, "logRetentionInDays", { type: "number", }); const vpc = new Vpc(this, vpcName, { name: vpcName, publicSubnets: ["10.0.1.0/24", "10.0.2.0/24"], }); new Eks(this, "EksModule", { clusterName: "my-kubernetes-cluster", subnetIds: Token.asList(vpc.publicSubnetsOutput), cloudwatchLogGroupRetentionInDays: logRetention.numberValue, }); }}
Initially, CDKTF will resolve Token.asList(vpc.publicSubnetsOutput)
to ["#{TOKEN[TOKEN.9]}"]
and logRetention.numberValue
to a big negative number like -123828381238238
.
Later in synthesis, CDKTF will resolve the token to ${module.<module id>.public_subnets}
and ${var.logRetentionInDays}
.
{ "module": { "helloterraEksModule5DDB67AE": { "cluster_name": "my-kubernetes-cluster", "subnets": "${module.helloterraMyVpc62D94C17.public_subnets}" } }}
Refer to the AWS CDK documentation for more detailed information about tokens.
Using Terraform's null
value
Some edge cases require passing the Terraform null
value to for example an attribute of a resource.
import { Token } from "cdktf";Token.nullValue();