Video Thumbnail for Lesson
8.1: Testing Terraform Code (Theory)

Testing Terraform Code (Theory)

In this lesson, we will discuss the importance of testing your Terraform code to ensure that your infrastructure-as-code configurations maintain high quality and continue to perform as expected.

We will also explore various testing techniques to prevent code rot in your infrastructure.

Code Rot

Code rot refers to the gradual degradation of a codebase over time due to external dependencies changing, other changes in the codebase impacting specific functions, or unapplied changes. In the context of Terraform and infrastructure, code rot may occur due to:

  • Out-of-band changes.
  • Unpinned versions of providers.
  • Deprecated external modules or resource types.
  • Unapplied changes to Terraform configurations.

Preventing Code Rot with Testing

To prevent code rot, we can perform various types of tests on our Terraform code:

  1. Static checks: Run built-in Terraform commands like terraform fmt, terraform validate, and terraform plan to check the formatting, validate configurations, and compare the desired state with the actual state, respectively. Use custom validation rules to further validate your infrastructure configurations.

  2. Third-party tools: Use tools like tflint, checkov, tfsec, and terrascan to perform additional checks on your codebase. Terraform Sentinel, available only for enterprise customers, provides security and compliance guarantees.

  3. Manual testing: Follow the standard Terraform workflow, running terraform init, terraform apply, and terraform destroy to test your configuration manually.

  4. Automated testing: Automate the manual testing steps using a shell script or a more robust method, such as utilizing a testing framework like TerraTest with Go to write complex tests and make assertions about your infrastructure.