Policy as code means writing rules ("every resource has a cost_center tag", "no public IPs in prod", "no deletes without approval") as code that runs automatically, instead of as a wiki page reviewers are supposed to remember.
There's no single right tool. There are layers, and each rule belongs in the cheapest layer that can enforce it reliably:
| Layer | When it runs | Can be bypassed? | Good for |
|---|---|---|---|
Variable validation, preconditions |
Every plan | No (it's in the code) | Input correctness, module contracts |
check blocks |
Every plan/apply | Warning only | Continuous health assertions |
| pre-commit (scanners, custom scripts) | On commit | Yes (--no-verify) |
Fast feedback |
| Static scanners in CI (Checkov, Trivy) | Every MR | Not if required | Known-bad configurations |
| Plan policy in CI (Conftest/OPA, Checkov on plan) | Every MR, after plan | Not if required | Organisation rules on real values |
| HCP Terraform policy sets (Sentinel, OPA, tfpolicy) | Every HCP run | Only with override permission | Central governance on HCP |
| Cloud-native policy (Azure Policy, AWS SCPs, GCP Org Policy) | Every API call, from any tool | No | The backstop for non-negotiables |
Rules that must hold, like "no storage account with public blob access", belong in cloud-native policy as well as CI, because people and other tools don't go through your Terraform pipeline.
One worked example on its own page: naming consistency validation with Conftest and pre-commit.
Native Terraform guardrails¶
Variable validation¶
Rejects bad inputs at plan time. Covered in variables.
Preconditions and postconditions¶
Contracts on resources, data sources and outputs. Covered in meta-arguments.
Check blocks¶
check blocks (Terraform 1.5+, OpenTofu 1.6+) run assertions at the end of every plan and apply and report failures as warnings. They never block. Use them for things you want to know about but that shouldn't stop a deploy:
check "app_health" {
# A scoped data source, only visible inside this check
data "http" "health" {
url = "https://${azurerm_linux_web_app.this.default_hostname}/healthz"
}
assert {
condition = data.http.health.status_code == 200
error_message = "Health endpoint returned ${data.http.health.status_code}."
}
}
check "cert_expiry" {
assert {
condition = timecmp(azurerm_key_vault_certificate.tls.certificate_attribute[0].expires, timeadd(plantimestamp(), "720h")) > 0
error_message = "TLS certificate expires within 30 days."
}
}
In HCP Terraform, check blocks power continuous validation: health assessments re-run them on a schedule and alert on failures. Outside HCP, a scheduled terraform plan gives you the same signal in your logs.
Conftest and OPA against plan JSON¶
Open Policy Agent evaluates Rego policies against JSON. Conftest is a CLI wrapper around OPA for config files. Pointed at terraform show -json output, they see resolved values: variables substituted, modules expanded, and the planned actions (create/update/delete/replace).
terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json
conftest test tfplan.json --policy policy/
Rego v1 syntax¶
OPA 1.0 (December 2024) made the if and contains keywords mandatory, and current Conftest releases use OPA v1. Older examples written as deny[msg] { ... } fail to parse. Write:
package main
import rego.v1
# Every taggable resource being created or updated must carry these tags
required_tags := {"environment", "cost_center", "owner"}
deny contains msg if {
rc := input.resource_changes[_]
rc.mode == "managed"
some action in rc.change.actions
action in {"create", "update"}
tags := object.get(rc.change.after, "tags", null)
tags != null
missing := required_tags - {k | some k, _ in tags}
count(missing) > 0
msg := sprintf("%s is missing required tags: %v", [rc.address, missing])
}
# No deletes or replacements without an explicit allow-list entry.
# Supply the list with: conftest test --data exceptions.yaml ...
# where exceptions.yaml contains `allowed_deletes: ["azurerm_x.y"]`
allowed_deletes := {a | some a in data.allowed_deletes}
deny contains msg if {
rc := input.resource_changes[_]
"delete" in rc.change.actions
not rc.address in allowed_deletes
msg := sprintf("%s would be deleted or replaced. Add it to allowed_deletes if intended.", [rc.address])
}
# Warn (don't fail) on public network access
warn contains msg if {
rc := input.resource_changes[_]
rc.change.after.public_network_access_enabled == true
msg := sprintf("%s has public network access enabled.", [rc.address])
}
import rego.v1 is harmless on OPA 1.x and makes the file also work on late 0.x versions. If you have a body of old v0 policies, conftest test --rego-version v0 buys time while you migrate (opa fmt --v0-v1 rewrites them).
Testing policies¶
package main_test
import rego.v1
import data.main
test_missing_tags_denied if {
plan := {"resource_changes": [{
"address": "azurerm_resource_group.x",
"mode": "managed",
"change": {"actions": ["create"], "after": {"tags": {"environment": "dev"}}},
}]}
count(main.deny) > 0 with input as plan
}
conftest verify --policy policy/
Useful plan JSON paths¶
| Path | Contains |
|---|---|
resource_changes[].address |
module.net.azurerm_subnet.this["aks"] |
resource_changes[].type / .mode |
Resource type; managed or data |
resource_changes[].change.actions |
["create"], ["update"], ["delete"], ["delete","create"] (replace), ["no-op"] |
resource_changes[].change.before / .after |
Attribute values (unknowns are absent from after) |
resource_changes[].change.after_unknown |
Which attributes are (known after apply) |
configuration |
The parsed configuration, including module calls and expressions |
prior_state |
State before the plan |
Sharing policies¶
Keep policies in their own repo, versioned, and pull them into pipelines with conftest pull (OCI registries, Git, HTTP) or a Git submodule. Atlantis has built-in Conftest policy checks with approval workflows (CI/CD).
Checkov custom policies¶
If you already run Checkov, simple attribute rules are quicker as YAML policies than as Rego:
# custom-policies/require_cost_center.yaml
metadata:
id: "CKV2_ACME_1"
name: "Resource groups must have a cost_center tag"
category: "GENERAL_SECURITY"
definition:
and:
- cond_type: attribute
resource_types: ["azurerm_resource_group"]
attribute: tags.cost_center
operator: exists
checkov -d . --external-checks-dir custom-policies
YAML policies can also express relationships ("every storage account is connected to a private endpoint") with cond_type: connection.
HCP Terraform: Sentinel, OPA and Terraform policy¶
If you run on HCP Terraform or Terraform Enterprise, policy sets attach to workspaces (and Stacks) and run on every plan with enforcement levels:
| Framework | Language | Notes |
|---|---|---|
| Sentinel | Sentinel DSL | HashiCorp's original; deep plan/state/config imports; advisory / soft-mandatory / hard-mandatory |
| OPA | Rego | Same Rego as Conftest, so policies can be shared with non-HCP pipelines |
| Terraform policy (tfpolicy) | HCL | Announced in 2026 as a public beta in HCP Terraform. Policies are HCL policy/enforce blocks, can look up resources and data sources at evaluation time, and are tested with a tfpolicy CLI. Supports Stacks as well as workspaces |
Terraform 1.16 shows a summary of HCP policy outcomes directly in CLI output for plan and apply.
If you're not on HCP, the Conftest pattern above gives you the same enforcement in GitLab CI.
Cloud-native policy: the backstop¶
Terraform-side policy only sees Terraform. Cloud-native policy sees every API call:
- Azure Policy:
Denyeffects for non-negotiables (allowed locations, no public IPs on NICs, storage HTTPS only),Modify/DeployIfNotExistsfor automatic remediation (diagnostic settings, tags), assigned at management group scope. Manage the definitions and assignments with Terraform in a dedicated foundation stack. - AWS: Service Control Policies and Resource Control Policies in Organizations, AWS Config rules.
- GCP: Organization Policy constraints.
Two interactions to plan for:
- A
Denypolicy makesterraform applyfail mid-run with aRequestDisallowedByPolicyerror. Mirror the important deny rules in CI policy so they fail at plan time instead. Modifypolicies that add tags create drift. Either add the tags in Terraform too, orignore_changesthose specific tag keys.
Choosing¶
| Situation | Start with |
|---|---|
| Module input rules | validation blocks |
| "This must be true about what I built" | Postconditions |
| Ongoing health signals | check blocks |
| Known insecure patterns | Checkov or Trivy |
| Organisation rules, GitLab CI | Conftest + Rego against plan JSON |
| Organisation rules, HCP Terraform | Sentinel, OPA or tfpolicy policy sets |
| Non-negotiable regardless of tool | Azure Policy / SCPs |