CDK for Terraform Amazing

source: https://learn.hashicorp.com/terraform/cdktf/cdktf-install

source: https://www.hashicorp.com/blog/cdk-for-terraform-enabling-python-and-typescript-support/

On Linux Install Terraform

Download package : https://www.terraform.io/downloads.html

# linux x86 
$ wget https://releases.hashicorp.com/terraform/0.12.28/terraform_0.12.28_linux_amd64.zip

$ unzip terraform_0.12.28_linux_amd64.zip 

$ echo $PATH

$ chmod +x terraform 

$ sudo mv terraform /usr/local/bin/

Install CDK for Terraform

https://learn.hashicorp.com/terraform/cdktf/cdktf-install#quick-start-tutorial

$ npm install --global cdktf-cli

$ npm install --global cdktf-cli@next

# Test cdktf
$ cdktf

$ cdktf deploy --help

$ mkdir typescript-docker && cd $_

$ cdktf init --template=typescript --local

# modify origin cdktf.json
{
  "language": "typescript",
  "app": "npm run --silent compile && node main.js",
  "terraformProviders": [
    "aws@~> 2.0"
  ]
}
# "aws@~> 2.0" to "docker"
{
  "language": "typescript",
  "app": "npm run --silent compile && node main.js",
  "terraformProviders": [
    "docker"
  ]
}

#main.ts
import { Construct } from 'constructs'
import { App, TerraformStack } from 'cdktf'
import { Container, Image } from './.gen/providers/docker'

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

    const dockerImage = new Image(this, 'nginxImage', {
      name: 'nginx:latest',
      keepLocally: false,
    })

    new Container(this, 'nginxContainer', {
      image: dockerImage.latest,
      name: 'tutorial',
      ports: [
        {
          internal: 80,
          external: 8000,
        },
      ],
    })
  }
}
    
const app = new App()
new MyStack(app, 'typescript-docker')
app.synth()

Install dependencies and deploy

$ cdktf get

$ cdktf deploy --auto-approve true

Delete

cdktf destroy --auto-approve true

202007028 Neil Kuan