Terraform & tests
Build infrastructure as a code (IaC) using test-later development (TLD) method
Using test-driven development (TDD) approach in software development is broadly used in industry for many years. When we are talking about infrastructure, it’s not as obvious and frequently used approach, but when we take a look on pyramid of tests and think about tools available for infrastructure as a code (IaC), then we can propose multiple approaches to do:
- unit tests using built-in tools available e.g. in Terraform like
terraform fmt
,terraform validate
or external programs like conftest - contract tests using validations for variables, lifecycle pre-conditions for resources or external tools like kitchen-terraform
- integration tests using
terratest
,localstack
or other local / non-production environments - end-to-end tests using also
terratest
As we have a lot of types of tests, we have also different approaches when and how to write them. In case of TDD there is common cycle - writing failing test (red phase), implementing code which causes that tests is succeeding (green phase) and adjusting code (refactor phase). For infrastructure sometimes it’s very hard to write tests before implementation e.g. validation rule variable can be created after variable is defined, not before, that’s why in many cases for IaC we can talk about test-later development (TLD) method.
Links
- Unit tests
- Conftest
- Module testing
- Terratest - automated tests for infrastructure code
- Kitchen-Terraform - verification of infrastructure
- Terratest - testing best practices
- Terraform Validator
- tfsec
- kube-score
- Infracost
- Test-Driven Development (TDD) for Infrastructure
- Testing HashiCorp Terraform
- Testing your HCL Modules in Terraform
- Testing Infrastructure as Code on Localhost
- How to Test Terraform Infrastructure Code
- Terraform with Terratest in Gitlab Pipeline
- Design by Contract in Terraform
- Test-Driven Development for Infrastructure
- Example with Terraform / AWS / S3
- Examples for Test-Driven Development (TDD) of infrastructure.
- Test-later development (TLD) - writing unit test after writing code considered harmful in test-driven development
- TDD vs TLD and what is the minimum code coverage needed