04.08.21

AWS Cloud Development Kit (CDK) for Terraform: Enabling TypeScript & Python Support

By Juan Ignacio Giro
AWS Cloud Development Kit (CDK) for Terraform - Enabling TypeScript & Python Support feature image

It’s not a leap to propose that Terraform is the DevOps cornerstone for Infrastructure as Code (IAC). Terraform’s adoption since its mid-2014 release to the software development landscape has been meteoric. More than 8000 organizations are using Terraform for infrastructure automation.

To successfully use the IAC tool, it’s important to optimize HashiCorp Configuration Language (HCL). HCL has become one of the most popular languages on GitHub. Typically though, it’s preferable to work with a familiar programming language rather than learning a new one. The good news here is that the Terraform community, in collaboration with AWS Cloud Development Kit (CDK), recently announced the support of TypeScript and Python for provisioning infrastructure using Terraform. Developers can leverage these languages to optimize the IAC’s tools many providers and modules.  

Today we’ll discuss how to use CDK for Terraform and the support of TypeScript and Python programming languages. But before that, let us quickly understand Terraform and AWS CDK.

Introduction to Terraform and AWS CDK

Terraform is the most popular infrastructure provisioning tool developed by HashiCorp in July 2014, which uses Infrastructure as Code to provision and manage the complete IT infrastructure. Terraform automatically creates models for the cloud infrastructure using code. In many ways, Terraform is very similar to AWS Cloudformation, an AWS service to build AWS infrastructure. We can use Terraform with all the popular cloud providers such as AWS, Azure, and Google Cloud.

AWS Cloud Development Kit (CDK) is a software development framework where we can model cloud applications using the programming languages familiar to us, use customized CloudFormation templates to provision applications, and deploy applications on AWS faster. The AWS CDK allows you to build highly scalable, highly reliable, cost-effective applications in the cloud without making us think about creating and configuring the underlying AWS infrastructure. The AWS CDK enables us to create cloud applications without even leaving the integrated development environment (IDE).

CDK for Terraform

CDK (Cloud Development Kit) for Terraform is an output product of deep collaboration between the AWS CDK team and Hashicorp. CDK for Terraform allows developers to use familiar programming languages such as Python and Terraform to define the cloud infrastructure and provision it through HashiCorp Terraform

CDK for Terraform uses the same programming constructs as AWS CDK. Still, instead of using CloudFormation, we use Terraform as a runtime engine, and we can produce a terraform configuration in JSON that terraform can understand. With recent CDK updates for Terraform, the engineers can now define the infrastructure using Python and TypeScript while leveraging providers and modules from the Terraform community.

Setting up a project

To run CDK for Terraform, install the below packages on your machine:

Once the prerequisites are in place, we can start setting up the project by installing CDK for Terraform CLI using npm (node package manager).

ubuntu@ubuntu:~$ sudo npm install -g cdktf-cli
/usr/local/bin/cdktf -> /usr/local/lib/node_modules/cdktf-cli/bin/cdktf
+ cdktf-cli@0.2.0
updated 3 packages in 13.34s

After installing cdktf-cli, create a project directory.

ubuntu@ubuntu:~$ mkdir cdk-demo
ubuntu@ubuntu:~$ cd cdk-demo/

From the project directory, initialize CDK for Terraform.

ubuntu@ubuntu:~/cdk-example$ cdktf init

[1] csharp
[2] java
[3] python
[4] python-pip
[5] typescript
[0] CANCEL

You can see, CDK for Terraform currently supports five programming languages, including TypeScript and Python. We will select 5, which is TypeScript. This will initialize a TypeScript project.

What template you want to use? [1...5 / 0]: 5

Initializing a project using the typescript template.

We will now set up the project. Please enter the details for your project.
If you want to exit, press ^C.

Project Name: (default: 'cdk-example') 
Project Description: (default: 'A simple getting started project for cdktf.') 

Detected Terraform Cloud token.

We will now set up Terraform Cloud for your project.

+ @types/node@14.14.37
+ typescript@4.2.3
added 2 packages from 43 contributors and audited 6 packages in 7.161s
found 0 vulnerabilities
=======
Your cdktf typescript project is ready!

When we run the ls command, we can see all the necessary files in the project directory.

ubuntu@ubuntu:~/cdk-demo$ ls
cdktf.json  main.ts       package.json       tsconfig.json
help        node_modules  package-lock.json

You have successfully set up a CDK Terraform project for TypeScript. Similarly, if you select option 3 when you run the init command, a Python project will get initialized.

TypeScript and Python for Terraform Configuration using CDKTF

Now open the above project in your favourite IDE, we will use Visual Studio here. You can see some default code is already present, and there is a place where you can add your logic to define the resources you want to deploy in the infrastructure.

visual studio code

Go to cdktf.json and add the below lines to configure it for AWS Terraform provider.

{
  "language": "typescript",
  "app": "npm run --silent compile && node main.js",
  "terraformProviders": [
    "aws@~> 2.0"
  ]
}

Now, run the get command to install the necessary dependencies for this project.

ubuntu@ubuntu:~/cdk-demo$ cdktf get
Generated typescript constructs in the output directory: .gen

Add the below code in the main.ts file. This code will provision a t2.micro AWS EC2 instance in region us-west-1.

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: 'apple',
        Address: '134 Loise Lane',
      },
    })

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

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

Once the code is ready, export the two environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. You will find these in the AWS management console.

ubuntu@ubuntu:~/cdk-demo$ export AWS_ACCESS_KEY_ID=**********************

ubuntu@ubuntu:~/cdk-demo$ export AWS_SECRET_ACCESS_KEY=***************************************

Finally, run the deploy command to run the project. 

ubuntu@ubuntu:~/cdk-demo$ cdktf deploy
Stack: typescript-aws
Resources
 + AWS_INSTANCE        typescriptaws_comp aws_instance.typescriptaws_compute_D9
                       ute                683B2F

Diff: 1 to create, 0 to update, 0 to delete.

Do you want to perform these actions?
  CDK for Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value:yes 

Deploying Stack: typescript-aws
Resources
 ✔ AWS_INSTANCE        typescriptaws_comp aws_instance.typescriptaws_compute_D9
                       ute                683B2F

Summary: 1 created, 0 updated, 0 destroyed.
Output: typescriptaws_publicip_EEB4927B = 54.153.7.27

The output above shows the instance is ready.

Go to the EC2 dashboard in the AWS management console, and you will find the instance up and running.

instance state

We can run the destroy command to delete the Terraform infrastructure, in this case, an AWS EC2 instance.

ubuntu@ubuntu:~/cdk-demo$ cdktf destroy
Stack: typescript-aws
Resources
 - AWS_INSTANCE         typescriptaws_compu aws_instance.typescriptaws_compute_D968
                        te                  3B2F

Diff: 0 to create, 0 to update, 1 to delete.
Destroying Stack: typescript-aws
Resources
 ✔ AWS_INSTANCE        typescriptaws_comp aws_instance.typescriptaws_compute_D9
                       ute                683B2F

Summary: 1 destroyed.

You have successfully configured infrastructure through Terraform in TypeScript. Similarly, you can initialize and configure a Python project also and provision infrastructure using CDK for Terraform with Python instead.

Conclusion

The AWS CDK for Terraform is a combination of AWS CDK and Terraform and its huge advantage lies in helping engineers avoid the steep learning curve of needing to learn HashiCorp Configuration Language to work with Terraform. The release means you can instead work with a preferred programming language option to write Terraform infrastructure code in your IDE. 


Caylent provides a critical DevOps-as-a-Service function to high growth companies looking for expert support with Kubernetes, cloud security, cloud infrastructure, and CI/CD pipelines. Our managed and consulting services are a more cost-effective option than hiring in-house, and we scale as your team and company grow. Check out some of the use cases, learn how we work with clients, and read more about our DevOps-as-a-Service offering.