Skip to main content
Terraform can understand configurations written in either HashiCorp Configuration Language (HCL) syntax or JSON. Because neither of these is a programming language, Terraform has developed ways to enable users to request and publish named values. These are: You may need to occasionally use these elements in your CDK Terrain (CDKTN) application instead of passing data through the conventions available in your preferred programming language.

Input Variables

You can define Terraform variables as input parameters to customize stacks and modules. For example, rather than hardcoding the number and type of AWS EC2 instances to provision, you can define a variable that lets users change these parameters based on their needs.

When to use Input Variables

Variables are useful when you plan to synthesize your CDKTN application into a JSON configuration file for Terraform. For example, when you are planning to store configurations and run Terraform inside HCP Terraform. If you plan to use CDKTN to manage your infrastructure, we recommend using your language’s APIs to consume the data you would normally pass through Terraform variables. You can read from disk (synchronously) or from the environment variables, just as you would in any normal program.
The synthesized Terraform configuration will contain any values that you pass directly to CDKTN constructs. This includes credentials and any other sensitive data provided as input for the cdktn application. If you plan to commit the generated cdk.tf.json to version control, use input variables for secrets instead.

Define Input Variables

You must specify values in exactly the same way as you would in an HCL configuration file. Refer to the Terraform variables documentation for details. The CDKTN CLI currently also supports configuration via environment variables. The following example uses TerraformVariable to provide inputs to resources.
const imageId = new TerraformVariable(this, "imageId", {
  type: "string",
  default: "ami-abcde123",
  description: "What AMI to use to create an instance",
});
new Instance(this, "hello", {
  ami: imageId.value,
  instanceType: "t2.micro",
});

Define Complex Input Variables

const nodeGroupConfig = new TerraformVariable(this, "node-group-config", {
  type: VariableType.object({
    node_group_name: VariableType.STRING,
    instance_types: VariableType.list(VariableType.STRING),
    min_size: VariableType.NUMBER,
    desired_size: VariableType.NUMBER,
    max_size: VariableType.NUMBER,
  }),
  nullable: false,
  description: "Node group configuration",
});

new TerraformResource(this, "resource", {
  nodeGroupConfig: nodeGroupConfig.value,
});

Passing Input Variables to CDKTN

You can pass input variables to cdktn diff, cdktn deploy, and cdktn destroy in the following ways:
  • Environment variable: TF_VAR_imageId=ami-abcde123
  • --var CLI option: cdktn deploy --var='imageId=ami-abcde123'
  • --var-file CLI option: cdktn deploy --var-file=/path/to/variables.tfvars
  • Auto-loaded configuration files: We auto-load *.auto.tfvars and terraform.tfvars files found in the current working directory. Refer to the Terraform documentation for details.

Local Values

A Terraform local assigns a name to an expression to allow repeated usage. They are similar to a local variables in a programming language.

When to Use Local Values

Use local values when you need use Terraform functions to transform data that is only available when Terraform (or OpenTofu) applies a configuration. For example, instance IDs that cloud providers assign upon creation. When values are available before synthesizing your code, we recommend using native programming language features to modify values instead.

Define Local Values

The following example uses TerraformLocal to create a local value.
const commonTags = new TerraformLocal(this, "common_tags", {
  Service: "service_name",
  Owner: "owner",
});

new Instance(this, "example", {
  ami: "ami-abcde123",
  instanceType: "t2.micro",
  tags: commonTags.expression,
});
When you run cdktn synth the TerraformLocal synthesizes to the following JSON.
"locals": {
    "common_tags": {
      "Service": "service_name",
      "Owner": "owner"
    }
}
...
"resource": {
  "aws_instance": {
    "example": {
      "tags": "${local.common_tags}"
    }
  }
}

Output Values

You can define Terraform outputs to export structured data about your resources. Terraform prints the output value for the user after it applies infrastructure changes, and you can use this information as a data source for other Terraform workspaces.

When to use Output Values

Use outputs to make data from Terraform resources and data sources available for further consumption or to share data between stacks. Outputs are particularly useful when you need to access data that is only known after Terraform applies the configuration. For example, you may want to get the URL of a newly provisioned server. When values are available before synthesizing your code, we recommend using the functionality in your preferred programming language to supply this data as direct inputs. The following example uses a TerraformOutput to create an output.
import { TerraformLocal, TerraformStack, TerraformVariable } from "cdktn";
import { Construct } from "constructs";
import { App, TerraformOutput } from "cdktn";
interface OutputVariableStackConfig {
  readonly myDomain: string;
}

class OutputVariableStack extends TerraformStack {
  constructor(
    scope: Construct,
    name: string,
    config: OutputVariableStackConfig,
  ) {
    super(scope, name);

    const { myDomain } = config;

    new TerraformOutput(this, "my-domain", {
      value: myDomain,
    });
  }
}

const app = new App();
new OutputVariableStack(app, "cdktn-producer", {
  myDomain: "example.com",
});
app.synth();

Define Output Values

To access outputs, use the _output suffix for Python and the Output suffix for other languages. Outputs return an HCL expression representing the underlying Terraform resource, so the return type must always be string. When TerraformOutput is any other type than string, you must add a typecast to compile the application (e.g. mod.numberOutput as number). If a module returns a list, you must use an escape hatch to access items or loop over it. Refer to the Resources page for more information about how to use escape hatches. The following Typescript example uses TerraformOutput to create an output for a Random provider resource.
import { TerraformLocal, TerraformStack, TerraformVariable } from "cdktn";
import { Construct } from "constructs";
import { App, TerraformOutput } from "cdktn";
import { RandomProvider } from "@cdktn/provider-random/lib/provider";
import { Pet } from "@cdktn/provider-random/lib/pet";
class OutputsUsageStack extends TerraformStack {
  constructor(scope: Construct, name: string) {
    super(scope, name);

    new RandomProvider(this, "random", {});
    const pet = new Pet(this, "pet", {});

    new TerraformOutput(this, "random-pet", {
      value: pet.id,
    });
  }
}

const app = new App();
new OutputsUsageStack(app, "outputs-usage");
app.synth();
When you run cdktn synth, CDKTN synthesizes the code to the following JSON configuration.
"output": {
  "random-pet": {
    "value": "${random_pet.pet.id}"
  }
}
When you run cdktn deploy, CDKTN displays the following output.
Deploying Stack: cdktn-demo
Resources
 ✔ RANDOM_PET           pet                 random_pet.pet

Summary: 1 created, 0 updated, 0 destroyed.

Output: random-pet = choice-haddock

Define & Reference Outputs via Remote State

The following example uses outputs to share data between stacks, each of which has a remote backend to store the Terraform state files remotely.
import { TerraformLocal, TerraformStack, TerraformVariable } from "cdktn";
import { Construct } from "constructs";
import { App, TerraformOutput } from "cdktn";
import {
  CloudBackend,
  DataTerraformRemoteState,
  NamedCloudWorkspace,
} from "cdktn";

class Producer extends TerraformStack {
  constructor(scope: Construct, name: string) {
    super(scope, name);

    new CloudBackend(this, {
      organization: "hashicorp",
      workspaces: new NamedCloudWorkspace("producer"),
    });

    new RandomProvider(this, "random", {});
    const pet = new Pet(this, "pet", {});

    new TerraformOutput(this, "random-pet", {
      value: pet.id,
    });
  }
}

class Consumer extends TerraformStack {
  constructor(scope: Construct, name: string) {
    super(scope, name);

    new CloudBackend(this, {
      organization: "hashicorp",
      workspaces: new NamedCloudWorkspace("consumer"),
    });

    const remoteState = new DataTerraformRemoteState(this, "remote-pet", {
      organization: "hashicorp",
      workspaces: {
        name: "producer",
      },
    });

    new TerraformOutput(this, "random-remote-pet", {
      value: remoteState.getString("random-pet"),
    });
  }
}

const app = new App();
new Producer(app, "cdktn-producer");
new Consumer(app, "cdktn-consumer");
app.synth();