Getting started with CDK for Terraform 
Tags: cdktf, terraform, python
Published: 2020-07-23 16:13:16

---
title: Getting started with CDK for Terraform 
published: true
description: Getting started with CDK for Terraform
tags: cdktf, terraform, python
cover_image: https://asciinema.org/a/349186.png
---

### CDK for Terraform

Hashicorp recently announced `cdktf` Cloud Development Kit for Terraform which currently supports `Python3` and `Typescript`.

With `cdktf` we can write Terraform code in `Python3` or `Typescript` instead of `HCL` which is the default language for Terraform.

Well, I thought of giving it a try and check out how it works out with `Python3`.

# Install cdktf

To install the most recent stable release of cdktf, use npm.

```shell
npm install --global cdktf-cli
```

To get up to date with the cutting edge development version

```shell
npm install --global cdktf-cli@next
```

Once the installation is done you can check the cdktf installation via `cdktf`


```shell
Commands:
  cdktf deploy [OPTIONS]   Deploy the given stack
  cdktf destroy [OPTIONS]  Destroy the given stack
  cdktf diff [OPTIONS]     Perform a diff (terraform plan) for the given stack
  cdktf get [OPTIONS]      Generate CDK Constructs for Terraform providers and modules.
  cdktf init [OPTIONS]     Create a new cdktf project from a template.
  cdktf login              Retrieves an API token to connect to Terraform Cloud.
  cdktf synth [OPTIONS]    Synthesizes Terraform code for the given app in a directory.                                                                                                                                  [aliases: synthesize]

Options:
  --version          Show version number                                                                                                                                                                                             [boolean]
  --disable-logging  Dont write log files. Supported using the env CDKTF_DISABLE_LOGGING.                                                                                                                            [boolean] [default: true]
  --log-level        Which log level should be written. Only supported via setting the env CDKTF_LOG_LEVEL                                                                                                                            [string]
  -h, --help         Show help                                                                                                                                                                                                       [boolean]

Options can be specified via environment variables with the "CDKTF_" prefix (e.g. "CDKTF_OUTPUT")
```

Okay now, let's do some real work we will create a project where we will deploy Nginx on top of Docker using `cdktf` and Python3. For the Typescript example please check [terraform-cdk](https://github.com/hashicorp/terraform-cdk/tree/master/examples/typescript-docker).

Create a directory by any name in our case we will use below the `python-docker`


```shell
mkdir python-docker && cd $_
```

Initialize the project with the init command. We will use the `--local` flag so that the infrastructure state will be stored locally.


```shell
cdktf init --template=python --local
```


Make sure you pass `python` and not `python3` else you will get below error


```shell
Invalid values:
  Argument: template, Given: "python3", Choices: "python", "typescript"

```


`cdktf` will generate the template for us, in our case, we will be using docker to get Nginx running so make sure to change the provider in `cdktf.json`


```shell
{
  "language": "python",
  "app": "pipenv run ./main.py",
  "terraformProviders": ["docker"],
  "codeMakerOutput": "imports"
}
```

Run the get command to download the dependencies for using Docker with Python.


```shell
cdktf get
```

Now add your code in `main.py` file for building Docker


First import the Docker provider, this means the imports is a local directory created by the above command

```shell
from imports.docker import Image, Container
```

and later add below code


```shell
docker_image = Image(self, 'nginx-latest', name='nginx:latest', keep_locally=False)
        
Container(self, 'nginx-cdktf', name='nginx-python-cdktf',
                  image=docker_image.name, ports=[
                      {
                          'internal': 80,
                          'external': 8000
                      }], privileged=False)

```


Add the dependencies in `Pipenv` file in our case 

```shell
[packages]
constructs="3.0.4"
cdktf="0.0.12"
```

Pipenv will throw an error if you don't define the version for the packages


Run `pipenv` to get all the dependencies to install the pipenv check the official website [pipenv](https://pipenv.pypa.io/en/latest/)


```shell
pipenv install
```

Now compile and generate Terraform configuration

```shell
cdktf synth
```

The above command will create a folder called cdktf.out that contains all Terraform JSON configuration that was generated.

We can run the regular Terraform commands

```shell
cd cdktf.out
terraform init
terraform plan
terraform apply
```

OR

We can deploy

```shell
cdktf deploy
```

### Lets see a demo

[![asciicast](https://asciinema.org/a/349186.png)](https://asciinema.org/a/349186)