Calculate project
Contact us
Calculate project

Creating terraform infrastructure via cdktf

Oleh Tsymbal
Oleh Tsymbal
founder, cloud solution architect
Finish date: 28 March 2020

Creating terraform infrastructure via cdktf (Part one: Introduction\Setup)

Intro

Approximately 4 years ago I faced one very common but sometimes too overused pattern in terraform configuration - with a count.
You can see it in any community terraform module, like:

variable "s3_buckets" {
    type = list(string)s
    default = ["1bucket", "2bucket", "3bucket"]
}
resource "aws_s3_bucket" "s3-module" {
    count = length(var.s3_buckets)
}

It could produce some undesired changes when we just changed elements order or deleted some of them.

If we had had for_each or cdktf that time... but 3 years ago we didn't have another way to do it. However, since Terraform version >= 12, we can use `fore_each in our configuration. It has made our life much better.

variable "s3_buckets" {
    type = map(object({
        acl = string
    }))
    default = {
        1bucket = {
            acl = "private"
        }
    }
}
resource "aws_s3_bucket" "s3-module" {
    for_each = var.s3_buckets
    acl      = each.value.acl
}

As a result, it will not break anything even you delete something or change the order.

The count is still not so bad if you just practice, or you don't have other variants (you have only arrays in some data sources, and conversion to an object is useless).

Better way

But what if I tell you that we have a better approach?

Pulumi

It was my first attempt to reimagine my IaC vision. I was so inspired to use it, made some test configurations but... Pulumi is not a true open-source project, it doesn't have any collaboration alternatives except their cloud. In case if my company can afford to buy an enterprise plan, some very small companies cannot. So it can be hard to recommend it to other people. I still think that Pulumi is a great product, but maybe not for everyone.

Cdktf

Approximately 1 year ago I was pleasantly surprised, that Terraform developed their own CDK (In collaboration with Aws if I am not mistaken). And you can simplify your terraform code (or make it worse :) ) without using terraform-specific functions.

Cdkf setup

Create project

Terraform guys recommend installing cdktf globally (I don't know why, because I want to keep my OS clean as much as possible) and don't use npx.

That's why I just copy-paste this package.json file across my projects:

{
  "name": "terraform",
  "version": "1.0.0",
  "main": "main.js",
  "types": "main.ts",
  "license": "MIT",
  "private": true,
  "scripts": {
    "get": "cdktf get",
    "plan": "cdktf diff",
    "build": "cdktf get && tsc",
    "synth": "cdktf synth",
    "apply": "cdktf deploy",
    "terraform:apply": "terraform -chdir=cdktf.out apply",
    "terraform:destroy": "terraform -chdir=cdktf.out destroy",
    "terraform:plan": "terraform -chdir=cdktf.out plan",
    "destroy": "cdktf destroy",
    "compile": "tsc --pretty",
    "watch": "tsc -w",
    "upgrade": "npm i cdktf@latest cdktf-cli@latest",
    "upgrade:next": "npm i cdktf@next cdktf-cli@next"
  },
  "engines": {
    "node": ">=10.12"
  },
  "dependencies": {
    "cdktf": "^0.2.0",
    "constructs": "^3.3.68"
  },
  "devDependencies": {
    "@types/node": "^14.14.10",
    "cdktf-cli": "^0.2.0",
    "typescript": "^4.2.3"
  }
}

But if you prefer building it from scratch you can safely follow this link:

https://learn.hashicorp.com/tutorials/terraform/cdktf-build?in=terraform/cdktf

Then just copy additional commands from my package.json file.

Modify tsconfig.json

Also, I'd like to have absolute imports and separated directories for my code, that's why I will change tsconfig.json file (of you can copy-paste it from here).

{
  "compilerOptions": {
    "baseUrl": "src", // added for source code dir
    "alwaysStrict": true,
    "charset": "utf8",
    "declaration": true,
    "experimentalDecorators": true,
    "inlineSourceMap": true,
    "inlineSources": true,
    "lib": ["es2018"],
    "paths": {
      "*": ["*"]
    },
    "outDir": "./dist", // here we will have or js code
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "resolveJsonModule": true,
    "strict": true,
    "strictNullChecks": true,
    "strictPropertyInitialization": true,
    "stripInternal": true,
    "target": "es6"
  },
  "include": ["src"],
  "exclude": ["node_modules"],
  "moduleDirectories": ["node_modules", "src"]
}

Compare it with:

https://github.com/hashicorp/terraform-cdk/blob/main/examples/typescript/aws/tsconfig.json

Final touches

In case if you prefer using src folder you also have to correspondingly change your cdktf.json file.

{
  "language": "typescript",
  "app": "npm run --silent compile &&  NODE_PATH=./dist node dist/main.js",
  "terraformProviders": [
    "aws@~> 2.0"
  ],
  "context": {
    "excludeStackIdFromLogicalIds": "true",
    "allowSepCharsInLogicalIds": "true"
  }
}

Also, you can notice that I use main.js instead of index.js

Install required packages

After it we can run npm install and create src firectory.

In the next chapter, we will setup additional packages and make a simple configuration for AWS.

Clap if you like it!

Interested in our services?

Checked

What's next?

1
We contact you
We’ll contact you within 24 hours with more information on our next steps. In the meantime, you can check out our case studies and our blog
2
Collect requirements
Our next step will be to collect all the requirements for your project, clarify your business objectives, and expectations towards our cooperation
3
Proposal
After that, we’ll develop a proposal for you.

Services

  • Development
  • Advisory
  • Infrastructure
RabbitPeepers LLC
contact@rabbitpeepers.com
Kyiv, Ukraine
Delaware, US
PrivacyTerms © 2019-2021