CDK for Terraform CLI

0.21.0 · active · verified Wed Apr 22

CDK for Terraform (cdktf-cli) provides a command-line interface for developing and deploying Terraform configurations using familiar programming languages like TypeScript, Python, Go, C#, and Java. It allows developers to define infrastructure as code using object-oriented principles and high-level abstractions, which are then synthesized into Terraform HCL. The current stable version is 0.21.0, with frequent patch and minor releases occurring roughly every 1-2 weeks, indicating active development and a rapid release cadence. This approach differentiates it from writing raw HCL by enabling programmatic control, reusability of components through custom constructs, and leveraging existing language ecosystems for comprehensive testing, static analysis, and integrated development tooling. It aims to bridge the gap between traditional software development paradigms and the provisioning of cloud infrastructure.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a new CDKTF project, define an AWS S3 bucket using TypeScript, and then deploy and destroy the infrastructure using the `cdktf` CLI commands.

// First, initialize a new CDKTF project (run these commands in your terminal):
// mkdir my-cdktf-project
// cd my-cdktf-project
// npx cdktf init --template="typescript" --local --project-name="my-s3-app" --stack-name="dev"
//
// When prompted, select 'typescript' as the language and choose an example like AWS S3 bucket.
//
// After initialization, modify the generated 'main.ts' file (e.g., in 'main.ts' or 'src/main.ts')
// to define an S3 bucket. You might need to install the AWS provider: 'npm i @cdktf/provider-aws'

import { Construct } from 'constructs';
import { App, TerraformStack, TerraformOutput } from 'cdktf';
import { AwsProvider } from '@cdktf/provider-aws/lib/provider';
import { S3Bucket } from '@cdktf/provider-aws/lib/s3-bucket';

class MyS3Stack extends TerraformStack {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    new AwsProvider(this, 'aws', {
      region: 'us-east-1',
    });

    const bucket = new S3Bucket(this, 'my-unique-cdktf-bucket', {
      bucket: `my-cdktf-example-bucket-${Math.random().toString(36).substring(2, 7)}`,
      acl: 'private',
      tags: {
        Environment: 'Development',
        ManagedBy: 'CDKTF',
      },
    });

    new TerraformOutput(this, 'bucket_name', {
      value: bucket.bucket,
      description: 'The name of the S3 bucket created by CDKTF.',
    });
  }
}

const app = new App();
new MyS3Stack(app, 'my-s3-stack');
app.synth();

// To deploy this infrastructure, navigate to your project root in the terminal and run:
// npx cdktf deploy
//
// To destroy the deployed resources:
// npx cdktf destroy

view raw JSON →