Terraform 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.

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.

Last modified July 21, 2024: update (e2ae86c)