Cloud Development Kit for Terrafrom or CDKTF as it is commonly referred to is a tool kit that allows you to leverage the advantages of Terrafrom from within a high-level programming language such as TypeScript, Python, Java, C#, or Go. CDKTF automatically extracts the schema from Terraform providers and modules to generate the necessary classes for your application. We can use CDKTF with every provider that is avaiable on the Terrafrom registry.
In this post, we will look at an example of using CDKTF with Python to provision resources on a Palo Alto Networks Panorama. I chose a Palo Alto Networks Panorama as the target here because I am from a network engineering background.
Installation
Hashicorp have well documented steps on how you can install CDKTF and can be found here.
Getting Started
Initialise a new Project
Once we have successfully installed CDKTF and verified our installation, we begin by initialising a cdktf project with an appropriate template. Here, we are using Python as our template.
Once the initialiation has been completed, you will notice that several new files and folders are created. The main.py file is where we will be writing our code.
Add a provider
Next, we need to add the provider that we will be using in our code. In our case it would be the PaloAltoNetworks/panos provider.
Once the provider has been added you would again notice a new folder called imports being created. This folder has sub-folders containing Python Classes that we can import and use in our script. If you observe closely, the sub-folders directly correpond to resources in the PaloAltoNetworks/panos provider.
Edit the code
We will now edit the code to import the provider and create a network object on Panorama by editing the class MyStack in our main.py file. Refer to the in-line comments in the snippet below for explanation.
Initialise and Generate Plan
Once we have updated the code, we initialise terraform and generate the plan by executing the cdktf diff command.
On closer observation of the command output, it is similar to the output of terrafrom plan command and it provides us a summary of the changes it will make.
Deploying the changes
To create the resource on Panorama we execute the cdktf deploy command. This will result in the network object being created on Panorama.
Bonus - Looping to create multiple objects
One of the hardest concepts to comprehend about Terraform for me was loops. CDKTF enables us to use the looping concepts from the high-level programming of our choice to create resouces. The below example shows how we can use python for loop to create multiple objects.