DEV Community

Stephanie Makori
Stephanie Makori

Posted on

Automating Terraform Testing: From Unit Tests to End-to-End Validation

Infrastructure as code (IaC) is powerful, but deploying untested changes can be risky. On Day 18 of my 30-Day Terraform Challenge, I focused on automating testing for Terraform code, covering unit tests, integration tests, and end-to-end tests, all tied together in a CI/CD pipeline.


Unit Tests

Unit tests are fast, cheap, and safe because they test your module plan only—no real resources are created. Each unit test ensures your resources are configured correctly, such as validating cluster names, instance types, and open ports. These tests catch configuration errors and bad variables before anything reaches production.

Unit tests run on pull requests, giving developers fast feedback and confidence that changes won’t break the module.


Integration Tests

Integration tests deploy real infrastructure, assert behavior, then destroy everything. They check how modules interact with actual cloud resources, like verifying that the application load balancer responds correctly and that EC2 instances are running as expected.

Integration tests run only on pushes to the main branch, because they are slower and use real AWS resources. Using defer destroy ensures all resources are cleaned up after the test, preventing cost leaks.


End-to-End Tests

End-to-end (E2E) tests validate the entire stack—from networking and databases to applications. They ensure that the full system works as a whole. E2E tests are slow and costlier, so they are run less frequently.


CI/CD Test Strategy

  • Unit tests run on pull requests (fast, free)
  • Integration tests run only on push to main (slower, real AWS)

Lessons Learned

Test Type Tool Deploys Real Infra Time Cost What It Catches
Unit terraform test No Seconds Free Config errors, bad variables
Integration Terratest Yes Minutes Low Resource behavior
End-to-End Terratest Yes 15–30 min Medium Full system issues
  • Integration vs End-to-End: Integration tests focus on a module in isolation, while E2E tests validate the full stack.
  • Unit tests on PRs → fast feedback
  • E2E tests less frequent → expensive & slower

Challenges & Fixes

  • Missing required variables → added dummy values for unit tests
  • Go module errors → used go mod tidy
  • Terraform syntax mistakes → corrected .tftest.hcl content
  • Application Load Balancer slow startup → added retry logic
  • AWS credentials setup → properly configured GitHub secrets

Apply Screenshot


Conclusion

Automated testing with Terraform ensures infrastructure deploys reliably and safely. Combining unit, integration, and E2E tests gives full confidence while minimizing cost and risk. With CI/CD, every commit is validated, enabling rapid and safe iteration.


Additional Resources

  • Terraform Test Documentation
  • Terratest Documentation
  • GitHub Actions Terraform Setup
  • Go Testing Package
  • AWS Documentation

Top comments (0)