Better Programming

Advice for programmers.

Follow publication

Member-only story

Testing Your Terraform Infrastructure Code With Python

mehdio
Better Programming
Published in
3 min readMay 25, 2022
Image by the author

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!

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

mehdio
mehdio

Written by mehdio

✍️ Data Engineering, Tech Career & Code | 🎥 https://www.youtube.com/@mehdio