# Terraform Testing Quick Start ## Quick Commands ```bash # Run all tests terraform test # Run tests with verbose output terraform test -verbose # Check formatting terraform fmt -check -recursive # Auto-format all files terraform fmt -recursive # Validate configuration terraform validate ``` ## Pre-Commit Checklist Before committing changes, ensure: - [ ] Code is formatted: `terraform fmt -recursive` - [ ] Configuration is valid: `terraform validate` - [ ] All tests pass: `terraform test` - [ ] No sensitive data is hardcoded ## Test File Locations - `tests/resource_groups.tftest.hcl` - Default resource group tests - `tests/custom_configuration.tftest.hcl` - Custom configuration tests - `tests/variable_validation.tftest.hcl` - Variable validation tests ## Common Test Scenarios ### Adding a New Test 1. Choose the appropriate test file based on what you're testing 2. Add a new `run` block with a descriptive name 3. Use `command = plan` for most tests 4. Add assertions with clear error messages 5. Run the specific test to verify it works Example: ```hcl run "my_new_test" { command = plan variables { resource_groups = { test = { name = "Test" } } } assert { condition = error_message = "Clear description of what failed" } } ``` ### Testing a Specific Feature ```bash # Run specific test file terraform test -filter=tests/custom_configuration.tftest.hcl # Run with verbose output for debugging terraform test -verbose -filter=tests/variable_validation.tftest.hcl ``` ## CI/CD Pipeline Tests run automatically on: - Every push to master - Every pull request Pipeline order: 1. TFLint 2. Tfsec 3. Checkov 4. **Terraform Test** ⬅ Your tests 5. SonarQube 6. Terraform Init/Plan/Apply ## Troubleshooting ### Test Fails Locally But Not in CI - Check Terraform version: `terraform version` (need >= 1.6.0) - Ensure environment variables are not interfering - Check for local `terraform.tfvars` overriding test values ### Test Fails in CI But Not Locally - Review CI job output for environment-specific issues - Verify mock credentials are properly set in CI - Check for provider version mismatches ### Format Check Fails ```bash # Fix automatically terraform fmt -recursive # Verify terraform fmt -check -recursive ``` ## Best Practices 1. **Write tests for new features**: Every new feature should have corresponding tests 2. **Test edge cases**: Include tests for empty values, minimum/maximum values, etc. 3. **Use descriptive names**: Test names should clearly indicate what they test 4. **Clear error messages**: Help future developers understand failures quickly 5. **Keep tests focused**: One test should verify one specific behavior ## Need Help? - Full documentation: [TESTING.md](../TESTING.md) - Terraform test docs: https://developer.hashicorp.com/terraform/language/tests - Module README: [README.md](../README.md)