terraform-cdk
Define infrastructure resources using programming constructs and provision them using HashiCorp Terraform
Top Related Projects
Pulumi - Infrastructure as Code in any programming language 🚀
The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code
A Pluggable Terraform Linter
Terragrunt is a flexible orchestration tool that allows Infrastructure as Code written in OpenTofu/Terraform to scale.
The Cloud Foundation toolkit provides GCP best practices as code.
A tool to bring existing Azure resources under Terraform's management
Quick Overview
The terraform-cdk repository by HashiCorp is a project that enables developers to use familiar programming languages to define cloud infrastructure using Terraform. It provides a Cloud Development Kit (CDK) for Terraform, allowing users to write infrastructure as code using TypeScript, Python, Java, C#, or Go, which is then synthesized into Terraform configuration files.
Pros
- Allows developers to use familiar programming languages instead of HCL
- Provides type safety and IDE autocompletion for infrastructure code
- Enables the use of software engineering practices like testing and version control for infrastructure
- Facilitates the creation of reusable infrastructure components
Cons
- Adds an additional layer of abstraction over Terraform
- May have a steeper learning curve for those already familiar with HCL
- Potential for version mismatches between CDK constructs and Terraform providers
- Limited community resources compared to traditional Terraform
Code Examples
- Defining an AWS S3 bucket in TypeScript:
import { Construct } from 'constructs';
import { App, TerraformStack } from 'cdktf';
import { AwsProvider, S3Bucket } from '@cdktf/provider-aws';
class MyStack extends TerraformStack {
constructor(scope: Construct, name: string) {
super(scope, name);
new AwsProvider(this, 'AWS', {
region: 'us-west-1',
});
new S3Bucket(this, 'MyBucket', {
bucket: 'my-terraform-cdk-bucket',
});
}
}
const app = new App();
new MyStack(app, 'my-stack');
app.synth();
- Creating an Azure Resource Group in Python:
from cdktf import App, TerraformStack
from constructs import Construct
from imports.azurerm import AzurermProvider, ResourceGroup
class MyStack(TerraformStack):
def __init__(self, scope: Construct, ns: str):
super().__init__(scope, ns)
AzurermProvider(self, "Azurerm")
ResourceGroup(self, "rg",
name="my-terraform-cdk-rg",
location="West Europe"
)
app = App()
MyStack(app, "azure-python")
app.synth()
- Defining a Google Cloud Storage bucket in Go:
package main
import (
"github.com/aws/constructs-go/constructs/v10"
"github.com/hashicorp/terraform-cdk-go/cdktf"
"github.com/hashicorp/terraform-cdk-go/cdktf/providers/google"
)
func NewMyStack(scope constructs.Construct, id string) cdktf.TerraformStack {
stack := cdktf.NewTerraformStack(scope, &id)
google.NewGoogleProvider(stack, jsii.String("Google"), &google.GoogleProviderConfig{
Project: jsii.String("my-project"),
Region: jsii.String("us-central1"),
})
google.NewStorageBucket(stack, jsii.String("my-bucket"), &google.StorageBucketConfig{
Name: jsii.String("my-terraform-cdk-bucket"),
Location: jsii.String("US"),
})
return stack
}
func main() {
app := cdktf.NewApp(nil)
NewMyStack(app, "gcp-go")
app.Synth()
}
Getting Started
-
Install the CDK for Terraform:
npm install -g cdktf-cli
-
Initialize a new CDK for Terraform project:
mkdir my-terraform-cdk-project cd my-terraform-cdk-project cdktf init --template=typescript
-
Define your infrastructure in the
main.ts
file. -
Synthesize and deploy your infrastructure:
c
Competitor Comparisons
Pulumi - Infrastructure as Code in any programming language 🚀
Pros of Pulumi
- Supports multiple programming languages (Python, TypeScript, Go, C#)
- More mature and feature-rich ecosystem
- Better support for custom resources and providers
Cons of Pulumi
- Steeper learning curve for those familiar with HCL
- Requires runtime for execution, unlike Terraform's stateless nature
- Less direct integration with existing Terraform modules
Code Comparison
Pulumi (TypeScript):
import * as aws from "@pulumi/aws";
const bucket = new aws.s3.Bucket("my-bucket", {
website: { indexDocument: "index.html" },
});
Terraform CDK (TypeScript):
import { Construct } from "constructs";
import { S3Bucket } from "@cdktf/provider-aws/lib/s3-bucket";
new S3Bucket(this, "my-bucket", {
website: { indexDocument: "index.html" },
});
Both Pulumi and Terraform CDK offer infrastructure-as-code solutions using familiar programming languages. Pulumi provides a wider range of language support and a more established ecosystem, while Terraform CDK leverages the existing Terraform provider ecosystem and maintains closer compatibility with Terraform workflows. The choice between the two often depends on team preferences, existing infrastructure, and specific project requirements.
The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code
Pros of AWS CDK
- More mature and widely adopted, with extensive documentation and community support
- Native integration with AWS services, offering a seamless experience for AWS-centric projects
- Supports multiple programming languages (TypeScript, Python, Java, C#)
Cons of AWS CDK
- Limited to AWS infrastructure, lacking support for multi-cloud or hybrid environments
- Steeper learning curve for those already familiar with Terraform's declarative approach
- Potential vendor lock-in due to tight coupling with AWS services
Code Comparison
AWS CDK (TypeScript):
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as cdk from 'aws-cdk-lib';
const vpc = new ec2.Vpc(this, 'MyVPC', {
maxAzs: 2
});
Terraform CDK (TypeScript):
import { Construct } from 'constructs';
import { App, TerraformStack } from 'cdktf';
import { AwsProvider, vpc } from '@cdktf/provider-aws';
const myVpc = new vpc.Vpc(this, 'MyVPC', {
cidrBlock: '10.0.0.0/16',
maxAzs: 2
});
Both CDKs allow infrastructure definition using familiar programming languages, but AWS CDK is more tightly integrated with AWS services, while Terraform CDK offers greater flexibility for multi-cloud deployments. The choice between them depends on project requirements, existing infrastructure, and team expertise.
A Pluggable Terraform Linter
Pros of tflint
- Lightweight and focused on linting Terraform code
- Extensive rule set for catching errors and enforcing best practices
- Can be easily integrated into CI/CD pipelines
Cons of tflint
- Limited to static analysis and linting
- Doesn't provide a way to programmatically define infrastructure
Code Comparison
tflint example:
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
terraform-cdk example:
import { Construct } from 'constructs';
import { App, TerraformStack } from 'cdktf';
import { AwsProvider, Instance } from './.gen/providers/aws';
class MyStack extends TerraformStack {
constructor(scope: Construct, name: string) {
super(scope, name);
new AwsProvider(this, 'AWS', {
region: 'us-west-1',
});
new Instance(this, 'HelloWorld', {
ami: 'ami-0c55b159cbfafe1f0',
instanceType: 't2.micro',
});
}
}
tflint focuses on analyzing existing Terraform code, while terraform-cdk allows for defining infrastructure using programming languages like TypeScript. tflint is more suitable for teams already using HCL, while terraform-cdk offers more flexibility and programmatic control over infrastructure definition.
Terragrunt is a flexible orchestration tool that allows Infrastructure as Code written in OpenTofu/Terraform to scale.
Pros of Terragrunt
- Simpler learning curve for existing Terraform users
- Better support for modular and reusable Terraform configurations
- Native integration with existing Terraform workflows and tools
Cons of Terragrunt
- Limited programming language options (primarily HCL and Go)
- Less flexibility in defining complex infrastructure logic compared to CDK
Code Comparison
Terragrunt:
terraform {
source = "git::git@github.com:foo/modules.git//app?ref=v0.0.3"
}
inputs = {
app_name = "my-app"
environment = "prod"
}
Terraform CDK:
import { Construct } from 'constructs';
import { App, TerraformStack } from 'cdktf';
import { AwsProvider } from '@cdktf/provider-aws';
class MyStack extends TerraformStack {
constructor(scope: Construct, name: string) {
super(scope, name);
new AwsProvider(this, 'AWS', { region: 'us-west-1' });
// Define your resources here
}
}
Both Terragrunt and Terraform CDK aim to enhance Terraform workflows, but they take different approaches. Terragrunt focuses on improving Terraform's modularity and reusability within its existing ecosystem, while Terraform CDK leverages the power of programming languages to define infrastructure. The choice between them depends on your team's preferences, existing skills, and specific project requirements.
The Cloud Foundation toolkit provides GCP best practices as code.
Pros of cloud-foundation-toolkit
- Specifically designed for Google Cloud Platform, offering deep integration and best practices
- Includes pre-built, production-ready templates for common GCP architectures
- Provides a comprehensive set of tools beyond just infrastructure-as-code, including policy enforcement and documentation generation
Cons of cloud-foundation-toolkit
- Limited to Google Cloud Platform, lacking multi-cloud support
- Steeper learning curve for users not familiar with GCP-specific concepts and tools
- Less flexibility in terms of language choice compared to terraform-cdk's multi-language support
Code Comparison
cloud-foundation-toolkit (using Deployment Manager):
resources:
- name: my-instance
type: compute.v1.instance
properties:
zone: us-central1-a
machineType: zones/us-central1-a/machineTypes/n1-standard-1
disks:
- deviceName: boot
type: PERSISTENT
boot: true
autoDelete: true
initializeParams:
sourceImage: projects/debian-cloud/global/images/family/debian-10
terraform-cdk (using TypeScript):
import { Construct } from 'constructs';
import { App, TerraformStack } from 'cdktf';
import { GoogleProvider, ComputeInstance } from './.gen/providers/google';
class MyStack extends TerraformStack {
constructor(scope: Construct, name: string) {
super(scope, name);
new GoogleProvider(this, 'google', { region: 'us-central1' });
new ComputeInstance(this, 'example', {
name: 'test-instance',
machineType: 'f1-micro',
zone: 'us-central1-a',
bootDisk: {
initializeParams: {
image: 'debian-cloud/debian-10',
},
},
});
}
}
A tool to bring existing Azure resources under Terraform's management
Pros of aztfexport
- Specifically designed for Azure resources, offering more targeted and optimized export capabilities
- Generates Terraform configurations directly from existing Azure resources, simplifying migration processes
- Lightweight and focused tool, easier to integrate into Azure-specific workflows
Cons of aztfexport
- Limited to Azure resources only, lacking cross-cloud provider support
- May not offer the same level of programmability and flexibility as terraform-cdk
- Potentially less community support and ecosystem integration compared to terraform-cdk
Code Comparison
aztfexport:
aztfexport resource-group my-resource-group
terraform-cdk:
import { App, TerraformStack } from 'cdktf';
import { AzurermProvider } from '@cdktf/provider-azurerm';
class MyStack extends TerraformStack {
constructor(scope: Construct, name: string) {
super(scope, name);
new AzurermProvider(this, 'azurerm', {});
// Define resources here
}
}
Summary
aztfexport is a specialized tool for exporting Azure resources to Terraform configurations, offering simplicity and Azure-specific optimizations. terraform-cdk, on the other hand, provides a more versatile and programmable approach to infrastructure as code, supporting multiple cloud providers but potentially requiring more setup and coding. The choice between the two depends on the specific use case, Azure focus, and desired level of programmability.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
CDK for Terraform
Cloud Development Kit for Terraform (CDKTF) allows you to use familiar programming languages to define cloud infrastructure and provision it through HashiCorp Terraform. This gives you access to the entire Terraform ecosystem without learning HashiCorp Configuration Language (HCL) and lets you leverage the power of your existing toolchain for testing, dependency management, etc.
We currently support TypeScript, Python, Java, C#, and Go.
CDKTF includes two packages:
- cdktf-cli - A CLI that allows users to run commands to initialize, import, and synthesize CDK for Terraform applications.
- cdktf - A library for defining Terraform resources using programming constructs.
Get Started
Choose a language:
Hands-on: Try the tutorials in the CDK for Terraform collection on HashiCorp Learn.
Documentation
Refer to the CDKTF documentation for more detail about how to build and manage CDKTF applications, including:
-
Application Architecture: Learn the tools and processes that CDKTF uses to leverage the Terraform ecosystem and convert code into Terraform configuration files. It also explains the major components of a CDKTF application and how those pieces fit together.
-
Project Setup: Learn how to create a new CDKTF project from a pre-built or custom template. Also learn how to convert an existing HCL project into a CDKTF application.
-
Unit Tests: Learn how to test your application in Typescript with jest.
-
Examples: Reference example projects in every supported language and review explanatory videos and other resources.
Community
The development team would love your feedback to help guide the project.
- Contribute using the CONTRIBUTING.md guide.
- Ask a question on the HashiCorp Discuss using the terraform-cdk category.
- Report a bug or request a new feature.
- Browse all open issues.
Build
About prerequisites, refer the followings.
Clone the project repository.
git clone https://github.com/hashicorp/terraform-cdk.git
Download dependencies.
cd terraform-cdk/
yarn install
Build the project and packages.
yarn build
Top Related Projects
Pulumi - Infrastructure as Code in any programming language 🚀
The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code
A Pluggable Terraform Linter
Terragrunt is a flexible orchestration tool that allows Infrastructure as Code written in OpenTofu/Terraform to scale.
The Cloud Foundation toolkit provides GCP best practices as code.
A tool to bring existing Azure resources under Terraform's management
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot