CDK for Terraform (CDKTF) lets developers define infrastructure in TypeScript, Python, Java, C#, or Go rather than writing Terraform HCL directly. It converts the program into Terraform configuration, usually JSON, which Terraform then processes with its providers. CDKTF is an additional layer over Terraform, not a replacement for its plan, apply, or state behavior; it does not directly support OpenTofu. section 11.3
A CDKTF project has three levels:
- A resource is an object corresponding to a Terraform resource block; resources also include data sources. section 11.3.3
- A stack contains resources and module calls. It roughly corresponds to a top-level module or workspace and has its own state. section 11.3.3
- An app collects stacks, including when there is only one. Add each stack to the app, then call app.synth() so CDKTF can build its internal data structures; an unadded stack is invisible to the app. section 11.3.3
Start and operate a Python project
Install Node and the CLI with npm install --global cdktf-cli@latest, then run cdktf init to generate a project interactively. For an experiment using the null and random providers, run cdktf provider add null and cdktf provider add random to install their language libraries. Define the providers and resources in a stack, add the stack to an app, and call app.synth(). Run cdktf synth to produce Terraform-readable configuration. Run cdktf deploy to synthesize again by default and execute Terraform’s plan-and-apply cycle; with multiple stacks, select one, for example cdktf deploy staging. Remove that environment with cdktf destroy staging. section 11.3.2 section 11.3.3 section 11.3.4
Listing 11.43 CDKTF example generated HCL
terraform { #1
required_providers { #2
null = {
version = "3.2.2"
source = "null"
}
random = {
version = "3.6.2"
source = "hashicorp/random"
}
}
backend "local" { #3
path = "/Users/robert/testing/cdktf/terraform.staging.tfstate"
}
}
provider "null" { #4
}
provider "random" {
}
resource "random_password" "my_password" {
length = 16 #5
special = false #5
}
resource "null_resource" "example" {
triggers = {
password = "${random_password.my_password.result}" #6
}
}
The generated HCL makes the translation concrete: Python-defined providers and resources become Terraform provider and resource blocks, including a password reference in a resource trigger. Generating HCL is optional; the usual synthesis output is JSON. section 11.3.4
Take care when inspecting HCL output: if generated HCL and JSON both define the same block, cdktf deploy fails because Terraform sees duplicate definitions. Delete the cdktf.out directory after generating HCL and before deploying. Choose CDKTF chiefly when a tool or product needs to generate infrastructure configurations, or when a team needs a familiar programming language. Changing languages does not remove the work of IaC testing, state management, or deployment practices, and the extra layer can complicate debugging. section 11.3.4 section 11.3.1
