All guides

Policy as code: test Terraform plans with OPA and Conftest

OPA's documentation describes policies that check the changes Terraform is about to make before it makes them. Conftest runs such a policy against the plan as JSON and returns a failing exit code when a deny rule matches.

An open laptop on a wooden table in front of bookshelves

What a plan policy checks

Open Policy Agent (OPA) is an open source, general-purpose policy engine. It provides a declarative language, Rego, that lets you specify policy as code. For Terraform, OPA's documentation describes the use: policies that test the changes in a Terraform plan before Terraform applies them.

Conftest is a utility for writing tests against structured configuration data. It relies on the Rego language from OPA for its policies.

The plan as JSON

Shell

terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json

The output has a resource_changes array. Each entry carries the address and type of one resource instance, and a change object that holds actions, before and after. The valid values of actions include ["create"], ["update"] and ["delete"]. A replacement is ["delete", "create"] or ["create", "delete"].

The reference for terraform show warns that with -json, sensitive values are displayed in plain text. Keep tfplan.json out of uploaded artifacts.

A deny rule in Rego

Save this as policy/terraform.rego:

Rego

package main

protected := {"aws_db_instance", "aws_s3_bucket", "aws_kms_key"}

deny contains msg if {
  some rc in input.resource_changes
  rc.type in protected
  "delete" in rc.change.actions
  msg := sprintf("%s would be deleted or replaced", [rc.address])
}

The three resource types in protected are the example's choice. List the types you want to guard.

  • Conftest looks for deny, violation and warn rules, and by default it looks in the main namespace.
  • OPA v1.0 requires the if and contains keywords when declaring rules. contains makes a rule multi-value, so deny is a set of messages.
  • some rc in input.resource_changes introduces rc for each item of the array.
  • "delete" in rc.change.actions is a membership test on the list of actions.

Run the policy with Conftest

Policies go in a directory called policy by default, and the --policy flag overrides that.

Shell

conftest test tfplan.json

This is the output of Conftest 0.71.1 for a plan made with Terraform v1.9.8 that replaced one S3 bucket and deleted another:

Text

FAIL - tfplan.json - main - aws_s3_bucket.data would be deleted or replaced
FAIL - tfplan.json - main - aws_s3_bucket.logs would be deleted or replaced

2 tests, 0 passed, 0 warnings, 2 failures, 0 exceptions

The command returned exit code 1. For a plan that only created a bucket, the same rule passed and the command returned 0. Conftest's documentation says it returns exit code 1 by default only when a policy has failed.

Warn or deny

A warn rule has the same shape as a deny rule. In the same test, the rule renamed to warn printed both messages as WARN lines and the command returned 0.

The --fail-on-warn flag changes the exit codes. The documentation lists 0 for no failures or warnings, 1 for no failures and one warning or more, and 2 for one failure or more.

To introduce a rule and keep pipelines passing, write it as warn first and rename it to deny later.

The check in CI

Add three steps after terraform init in the pull request workflow:

YAML

- run: terraform plan -input=false -out=tfplan
- run: terraform show -json tfplan > tfplan.json
- run: conftest test tfplan.json

Conftest's installation page lists the ways to put the binary on a runner: Homebrew, Scoop, a release download and the Docker image openpolicyagent/conftest. The --output flag selects the report format, and the documented formats include json, junit, github and sarif.

Sentinel, Terraform policy and Checkov

  • Sentinel is HashiCorp's policy-as-code framework, with a purpose-built policy language. HCP Terraform checks the plan against the policy set during each run, and its policy enforcement overview lists Sentinel, OPA and Terraform policy as its frameworks.
  • Terraform policy is HashiCorp's HCL-based framework. It requires Terraform v1.17 or later, and HashiCorp's comparison page recommends it for governance in Terraform workflows.
  • Checkov scans infrastructure as code files by static code analysis. Its page says it includes more than 750 predefined policies, and that custom policies are written in Python or YAML. Conftest's page describes policies that you write in Rego.

Where to start

  • Write the first rule for the change you most want to stop, such as the deletion of a data store.
  • Test each rule both ways. Plan a change that should fail and confirm the failure, then plan a change that should pass.
  • Start a new rule as warn, then rename it to deny.
  • Run the check on every pull request, against the plan file that the run saves.

Sources

Want a second pair of eyes on yours? We do this work for a living.

Book a call

More guides