Validate IaC in CI before merge
Every finding caught before merge is one not caught during an outage. Run a fixed gate: format, validate, policy, then a plan.
Procedure
- Format check that fails, without auto-fixing silently: terraform fmt -check -recursive || { echo "run terraform fmt"; exit 1; }
- Static validate without a backend: terraform init -backend=false -input=false terraform validate
- Lint and security policy: tflint --recursive checkov -d . --quiet --soft-fail-on LOW
- Validate against the real plan in a plan-only job with read-only credentials: terraform plan -lock-timeout=5m -out=tf.plan
- Run policy as code over the plan JSON (OPA/Conftest) so rules see resolved values, not source text: terraform show -json tf.plan | conftest test - --policy policies/
- Post the plan to the PR as a comment so a reviewer sees the diff; a plan only in CI logs is unreviewed.
- Keep the gate fast: cache
.terraformand providers between runs, or people learn to skip it. - Make the gate required in branch protection; an advisory check is one that gets merged past at 5 pm.
Pitfalls
terraform validatealone: it checks syntax and references, not policy, not a plan, not drift.Running
init -upgrade, which changes the lock file in a check job and produces spurious diffs.A plan job with write credentials that could apply if a later step misfires.
Policy that runs on HCL only, missing a value injected at plan time (a variable that resolves to a public bucket ACL).
Soft-failing everything, so the check is green on every PR and no one reads it.
Caching
.terraformacross branches, so a stale module version passes validate and only fails at apply.A plan step gated behind manual approval to read, so the plan is never reviewed before merge.
Verification
terraform fmt -check -recursive && terraform validate && tflint --recursive
conftest test <(terraform show -json tf.plan) --policy policies/ # exit 0
Report: the gate steps, a PR that failed each one, and the branch-protection setting making them required.