Skip to content

Unit Tests

Unit tests in Terraform are used to validate the behavior of individual resources or modules, ensuring that they function as expected when given specific input, thereby contributing to the robustness and reliability of the infrastructure as code.


In Terraform the smallest amount of code that could be considered a unit is a single reusable module.

Info

It's worth noting that Terraform code unit tests could be considered closer to integration tests due to the complex systems involved in creating infrastructure in the cloud. Certainly if you were to compare unit testing in a code language like Python, we're testing a lot more "stuff"* in Terraform even for a single module that creates a simple resource.

By stuff I mean lots of various API calls, underlying services like IAM or firewalls, can all be involved in creating even a simple resource like a storage account.

Basic requirements of a unit test

  1. Single reusable module
  2. An deployable example of that module
  3. Creating the resource using the example code (terraform apply)
  4. Testing the resource is deployed and works
  5. Destroying the deployed resource (terraform destroy)

These steps are pretty much exactly the same as for manual tests. The key difference is that step 4 would be executed as code in CI pipeline and the results would either inform a system or a person as to the results and/or perform some kind of step such as stopping a deployment if errored.