Advanced Terraform · Module 04
Testing and CI/CD
Catch problems before apply: formatting, validation, linting and security scans; unit and integration tests with terraform test and mock providers; a pull-request pipeline that plans, reviews and applies a saved plan; and policies that check the plan as code.
What you will learn
- Run fmt, validate, TFLint and a misconfiguration scanner locally and in pre-commit hooks
- Write terraform test files with run blocks, assertions, expect_failures and mock providers
- Build a CI pipeline that plans on pull requests and applies the reviewed saved plan
- Check plans against rules with OPA/conftest and know where Sentinel fits
Lessons
- Formatting, Validation, Linting and Scanning
Cheap checks first: terraform fmt and validate, TFLint for provider-aware mistakes, and Trivy or Checkov for insecure settings, wired into pre-commit and CI.
- Testing with terraform test
Test files (*.tftest.hcl) run plan or apply with chosen variables and assert on the result; expect_failures tests validation, and mock providers make fast unit tests without real infrastructure.
- Plan and Apply in a CI Pipeline
A pull request runs checks and terraform plan -out, posts the plan for review, and after approval applies exactly that saved plan, with short-lived OIDC credentials and one run at a time per state.
- Policy as Code on Terraform Plans
Turn rules such as "no privileged containers" or "every resource has an owner tag" into code that checks the JSON plan in CI with OPA and conftest, or with Sentinel in HCP Terraform.