CDK for Terraform (cdktf) in TypeScript: Quick Start

In this post, I am going to explain how to build an EC2 instance with CDK for Terraform (TypeScript).

Link: Build AWS Infrastructure with TypeScript


what is CDK for Terraform (cdktf)?

It is a Cloud Development Kit (CDK) developed by HashiCorp and AWS.

Currently, the following languages are available as preview to run Terraform:

  • TypeScript
  • Python
  • Java
  • C#


version

To use cdktf in TypeScript, check the versions by:

% terraform -v

% node -v

expected:

  • Terraform v0.12+
  • Node.js v12.16+


install cdktf

On Mac, you can run:

% brew install cdktf

% cdktf --version

0.2.2


init

% mkdir typescript-aws

% cd typescript-aws

% cdktf init --template="typescript" --local

% tree -a
.
├── .gitignore
├── cdktf.json
├── help
├── main.ts
├── node_modules
│   ├── .bin
│  ...

├── package-lock.json
├── package.json
└── tsconfig.json


install dependencies

Initially, I was stuck with a provider error:

% cdktf get

ERROR: Please specify providers or modules in "cdktf.json" config file

Adding AWS as the provider solved the issue.

% vim cdktf.json
{
  "language": "typescript",
  "app": "npm run --silent compile && node main.js",
  "terraformProviders": ["aws@~> 2.0"],
  "terraformModules": [],
  "context": {
    "excludeStackIdFromLogicalIds": "true",
"allowSepCharsInLogicalIds": "true"
  }
}

% cdktf get

Generated typescript constructs in the output directory: .gen


sample code: create EC2

Replace the content of main.ts with the following:

import { Construct } from 'constructs'
import { App, TerraformStack, TerraformOutput } from 'cdktf'
import { AwsProvider, Instance } from './.gen/providers/aws'

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

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

    const instance = new Instance(this, 'compute', {
      ami: 'ami-01456a894f71116f2',
      instanceType: 't2.micro',
      tags: {
        Name: 'TypeScript-Demo',
        fruit: 'blueberry',
        Address: '123 Main St',
      },
    })

    new TerraformOutput(this, 'public_ip', {
      value: instance.publicIp,
    })
  }
}

const app = new App()
new MyStack(app, 'typescript-aws')
app.synth()

TypeScript to Terraform

You can convert the code into Terraform format, then run terraform commands to check the plan and so on.

% cdktf synth

Generated Terraform code in the output directory: cdktf.out

% cd cdktf.out

% terraform plan


deploy & destroy

Also, you can use cdktf to deploy and destroy the resources directly.

% cdktf deploy


% cdktf destroy


Comments

Popular posts from this blog

Selenide: Quick Start

Minikube Installation for M1 Mac

Server Testing Tools: Serverspec, InSpec, Testinfra, Goss