Member-only story
Testing Your Terraform Infrastructure Code With Python
Let’s cover an API use case with Terraform HCL & Python

Today, most of the infrastructure code is done through Terraform. It’s been there for quite a while, has a strong community, and it’s multicloud. However, things start to be tricky when it comes to testing Terraform code. While Terraform uses its own language (HCL), its backend is written in Golang.
A good pattern for Terraform modules tests is terratest, but as you may have guessed, you will need to write these in Golang. Here we’re going to showcase how we can use plain Python with a powerful yet simple library tftest on existing Terraform HCL code.
Tftest
Tftest is a small Python library from Google. It enables you to do Terraform actions (plan|deploy|destroy) programmatically and retrieve the execution plan, output variables, etc.
The power of tftest lies with the potential combo with pytest
. Besides, Python has really good SDK support on the different cloud providers, which makes it nice for testing cloud infrastructure.
Case study
Our setup will involve a simple Cloud Run API (serverless container runtime), but you can apply the above method for any infrastructure you deploy!