Skip to content

Cloud Development Kit for Terraform (CDKTF)ยป

The Cloud Development Kit for Terraform (CDKTF) generates JSON Terraform configuration from code in C#, Python, TypeScript, Java, or Go. Spacelift fully supports CDKTF.

Building a custom runner imageยป

CDKTF requires packages and tools that are not included in the default Terraform runner. These dependencies are different for each supported programming language.

Luckily, extending the default runner Docker image to include these dependencies is easy. You will need to:

  • Create a Dockerfile file that installs the required tools and packages for the specific programming language you want to use (see below).
  • Build and publish the Docker image.
  • Configure the runner image to use in the stack settings.
1
2
3
4
5
6
FROM public.ecr.aws/spacelift/runner-terraform:latest

USER root
RUN apk add --no-cache nodejs npm
RUN npm install --global cdktf-cli@latest
USER spacelift
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
FROM public.ecr.aws/spacelift/runner-terraform:latest

USER root
RUN apk add --no-cache nodejs npm python3
RUN npm install --global cdktf-cli@latest
RUN python3 -m ensurepip \
  && python3 -m pip install --upgrade pip setuptools

USER spacelift
RUN pip3 install --user pipenv
ENV PATH="/home/spacelift/.local/bin:$PATH"
1
2
3
4
5
6
FROM public.ecr.aws/spacelift/runner-terraform:latest

USER root
RUN apk add --no-cache go nodejs npm
RUN npm install --global cdktf-cli@latest
USER spacelift

Synthesizing Terraform codeยป

Before Terraform can plan and apply changes to your infrastructure, CDKTF must turn your C#, Python, TypeScript, Java, or Go code into Terraform configuration code. That process is called synthesizing.

This step needs to happen before the Initializing phase of a run. This can be easily done by adding a few before_init hooks:

  • npm install
  • cdktf synth
  • cp cdktf.out/stacks/${TF_VAR_spacelift_stack_id}/cdk.tf.json .
  • pipenv install
  • cdktf synth
  • cp cdktf.out/stacks/${TF_VAR_spacelift_stack_id}/cdk.tf.json .
  • cdktf synth
  • cp cdktf.out/stacks/${TF_VAR_spacelift_stack_id}/cdk.tf.json .

Warning

If the Terraform state is managed by Spacelift, make sure to disable the local backend that CDKTF automatically adds if none is configured by adding the following command after the hooks mentioned above:

1
jq '.terraform.backend.local = null' cdk.tf.json > cdk.tf.json.tmp && mv cdk.tf.json.tmp cdk.tf.json