Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท Workflows and Collaboration

Terraform Testing, Policy as Code and Security Scanning

Build a safety net for Terraform: validate, tflint, terraform test, preconditions, static scanners such as Checkov and Trivy, OPA and Sentinel policy as code on plan JSON.

A plan tells you what Terraform will do, but not whether it is a good idea. Is the new bucket public? Does the database have encryption? Did someone create a 96-core instance in dev? Humans miss these things in a 1,500-line plan. This lesson builds layers of automatic checks, from fast and cheap to slow and thorough, and shows how policy as code keeps rules consistent.

The testing pyramid for infrastructure

flowchart TD
  A["Format and validate: seconds, no credentials"] --> B["Linters and static scanners: tflint, Checkov, Trivy"]
  B --> C["Plan-time tests: terraform test with command = plan, mock_provider"]
  C --> D["Policy checks on the plan JSON: OPA, Sentinel"]
  D --> E["Apply tests in a sandbox account: terraform test command = apply, Terratest"]

Run the cheap layers on every commit and the expensive ones less often.

Layer 1: fmt and validate

Terminal
terraform fmt -check -recursive
terraform init -backend=false
terraform validate

These catch syntax errors, wrong types and unknown references. They cannot catch a wrong instance type or an unsafe setting.

Layer 2: linting and static scanning

  • TFLint checks provider-specific mistakes: invalid instance types, deprecated arguments, missing required tags (with rules). Run tflint --init then tflint.
  • Checkov, Trivy (trivy config .) and similar scanners read the .tf files and flag insecure patterns: public buckets, unencrypted volumes, security groups open to 0.0.0.0/0, missing logging.
  • terraform-docs keeps documentation in sync (not a test, but part of the same hygiene).

Scanners work on code, so they see only what is literally written. Values that come from variables or modules may be unknown until plan time, which is why the next layers exist.

Layer 3: plan-time tests and conditions

Native terraform test (the modules lesson) asserts on planned values. Inside the configuration, precondition and postcondition blocks and check blocks encode assumptions:

HCL
data "aws_ami" "app" {
  most_recent = true
  owners      = ["self"]

  lifecycle {
    postcondition {
      condition     = self.architecture == "x86_64"
      error_message = "The AMI must be x86_64."
    }
  }
}

check "https_works" {
  data "http" "site" { url = "https://${aws_lb.main.dns_name}/health" }

  assert {
    condition     = data.http.site.status_code == 200
    error_message = "Health endpoint is not returning 200."
  }
}

A failed check prints a warning without stopping the run, which suits continuous validation of things that can break after apply. Preconditions and postconditions stop the run.

Layer 4: policy as code on the plan

terraform show -json tfplan produces the full planned change set as JSON. A policy engine evaluates rules against it:

  • OPA (Open Policy Agent) with Conftest uses the Rego language and is cloud and tool agnostic.
  • Sentinel is HashiCorp's policy language, built into HCP Terraform and Terraform Enterprise.
  • Cloud-specific guardrails (AWS Service Control Policies, Azure Policy) act as the last line of defense regardless of tool.

A Rego rule looks like this (read-only):

TEXT
package terraform

deny contains msg if {
  rc := input.resource_changes[_]
  rc.type == "aws_s3_bucket_public_access_block"
  rc.change.after.block_public_acls == false
  msg := sprintf("%s must block public ACLs", [rc.address])
}

The stand-in below does the same with Python: it loads a plan JSON and applies three rules (no public ingress, mandatory tags, approved instance types).

Python Policy checks on plan JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Layer 5: real apply tests

Some bugs only appear when real resources are created: IAM propagation delays, name collisions, subtle API behavior. Two options:

  • terraform test with command = apply (the default) creates resources, checks them and destroys them. Use a dedicated sandbox account and budget alerts.
  • Terratest (Go) deploys real infrastructure, then calls it (HTTP requests, SSH) before destroying it.

Because these tests cost money and minutes, run them nightly or on release branches rather than on every push.

Secrets and sensitive data

  • Mark variables and outputs sensitive = true, remembering they still appear in state (State Basics).
  • Never commit .tfvars files that hold secrets; scan commits with a secret scanner (gitleaks, trufflehog).
  • Prefer reading secrets from a manager (aws_secretsmanager_secret_version, Vault) at apply time, or generate them with the provider and store only references.
  • Terraform 1.10+ supports ephemeral values and resources for secrets that should never be stored in state, where providers support them.
Python Simple secret scan for tfvars

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which check needs no credentials and runs in seconds?

    fmt and validate are offline checks, ideal as the first CI gate.
  2. 2. What does policy as code evaluate?

    terraform show -json produces data that OPA or Sentinel can allow or deny.
  3. 3. How does a check block differ from a precondition?

    check blocks are for continuous validation that should not block changes.
  4. 4. Why are apply tests run less often than plan tests?

    Real deployments are valuable but slow and billable, so run them nightly or on releases.

Summary

  • Layer your checks: fmt/validate, linters and scanners, plan tests, policy on plan JSON, then sandbox apply tests.
  • TFLint, Checkov and Trivy catch known bad patterns in code; OPA and Sentinel enforce your own rules on plans.
  • Use precondition, postcondition and check blocks to encode assumptions in the configuration.
  • Keep secrets out of tfvars and Git; remember state stores values in plain text.
  • Run cheap checks on every commit and expensive ones on a schedule.

Next: A Web Stack on AWS