Turn a Human Rule into a Testable Decision
A payments team closes an incident review with one sentence in the action log: "Production customer data must stay in the EU." Everyone agrees, and nothing changes. Six months later an engineer creates a bucket in us-east-1 and nothing in the pipeline objects, because a sentence is not a control.
A building code works differently. The sentence in the code book is enforced by an inspector carrying a checklist that names what is inspected, when, what counts as a failure, and who signs the certificate. Policy as code is that checklist written so a machine can run it on every change. Most failed governance programmes wrote the sentence, wrapped it in a Rego file, and never decided what the machine should do when it could not answer.
Give every rule five fields before writing any code. A rule evaluated against the wrong input is a guess with a badge, and a rule with no unknown branch is worse: it converts missing information into a pass.
| Field | What it decides | Residency rule, filled in |
|---|---|---|
| Input | The artifact the decision reads: source HCL, a saved plan or a cost estimate | resource_changes in the saved plan |
| Scope | Resources, accounts, workspaces and operations covered — the usual site of overreach | Creates and updates of aws_s3_bucket, aws_db_instance and aws_dynamodb_table in production |
| Outcomes | Pass, fail, or unknown when a value exists only after apply | Pass if every region argument is in the approved list; fail if not; unknown if the region comes from a variable with no plan-time value |
| Enforcement owner | The team that may change the rule and the role that may approve an exception | platform-governance owns the rule; the data protection officer approves exceptions |
| Evidence | What remains after the run: rule id and version, address, artifact version, decision and actor | The policy result plus the run identifier |
The filled-in column is the residency rule from the review, and it is the shape every rule should take. A rule with no owner is edited by whoever is blocked by it, and a decision a reviewer cannot reconstruct a year later exists only in the present tense.
Figure 1 shows that path, including the branch most teams omit: an unknown value routed to a person rather than a green tick.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Review finding:
EU data must stay in the EU"] --> B["Name the input
saved plan JSON"]
B --> C["Bind the scope
account, resource types, operations"]
C --> D["Write three outcomes
pass, fail, unknown"]
D --> E["Assign two owners
rule author and exception approver"]
E --> F{"Decide at plan time"}
F -->|"condition true"| G["Pass and record evidence"]
F -->|"condition false"| H["Fail: name the resource and the fix"]
F -->|"value unknown"| I["Unknown: route to a reviewer"]
H --> J["Exception request
owner, reason, scope, expiry"]
I --> J
J --> K["Re-decide before the expiry date"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,E primary;
class B,C secondary;
class D,F primary;
class G ok;
class H danger;
class I,J,K warn;
Figure 2 adds the two boundaries that decide whether the system is trusted. Changing a policy is a code review on the policy repository, with a test that fails before the change and passes after. And an override is a named person accepting a specific risk for a specific period, not a permission level that quietly turns the light green.
Write the third outcome first
Ask what would make the rule unable to answer. A generated identifier, a CIDR assigned by the cloud, a name from the random provider. Decide now whether each blocks or waits: security-critical attributes should block, cosmetic ones should warn, and none should pass by accident.
Compare Terraform Policy, Sentinel and OPA by Execution Context
Three frameworks ship with HCP Terraform, and the choice is decided by where the decision must happen, not by which language a team enjoys.
Terraform policy is the only framework here that decides before providers are downloaded. It evaluates during terraform init, at plan time and again after apply, on workspaces and Stacks. HCP Terraform requires Terraform v1.17 or later while the tfpolicy install page lists v1.16, so treat 1.17 as the platform floor and re-read both pages at implementation time (policy enforcement).
Sentinel is HashiCorp's own DSL and evaluates the plan at the policy-check stage using the tfplan/v2 import, at advisory, soft-mandatory or hard-mandatory level. OPA runs Rego against the plan and, in HCP Terraform, offers only advisory and mandatory; the mandatory level is overridable by anyone with the manage-policy-overrides permission. Both support workspaces only.
| Dimension | Terraform policy | Sentinel | OPA |
|---|---|---|---|
| Language and files | HCL, .policy.hcl (provider_policy, resource_policy, module_policy) | Sentinel DSL, .sentinel | Rego, .rego |
| Evaluation stages | init, plan, post-apply | plan / policy check | plan / policy check |
| Enforcement levels | advisory, mandatory_overridable, mandatory | advisory, soft-mandatory, hard-mandatory | advisory, mandatory |
| Plan-data helpers | attrs, prior_attrs, core::getresources, core::getdatasource | tfplan/v2, manual iteration | full plan JSON, manual iteration |
| Supported surface | workspaces and Stacks | workspaces only | workspaces only in HCP; any CLI elsewhere |
| Floor to verify | Terraform 1.17+ on the platform | runtime pin; policy checks stop at Sentinel 0.40.x | agent evaluation needs Premium |
The differences that change designs are the helpers and the stages. In Sentinel or OPA, "every bucket needs a versioning resource" means iterating both collections and matching by attribute, and the match breaks when that attribute is unknown at plan time. Native policy offers core::getresources(type, filter) for the relationship and core::getdatasource for approved-value lookups such as an AMI allowlist; neither of the others can query a data source while evaluating.
Figure 3 follows the mechanics, including the branches that produce a misleading result.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Policy set stored in VCS"] --> B{"Which framework?"}
B -->|"Terraform policy"| C["Init stage
provider_policy, module_policy"]
B -->|"Sentinel"| D["Plan stage only
tfplan/v2"]
B -->|"OPA"| E["Plan stage only
plan JSON, Rego"]
C --> F{"Init condition"}
F -->|"fail"| G["Block before download"]
F -->|"pass"| H["Plan evaluation"]
D --> H
E --> H
H --> I{"Decision"}
I -->|"pass"| J["Apply the saved plan"]
I -->|"advisory"| J
I -->|"mandatory"| K["Stop the run"]
I -->|"override"| L["Stop, record actor and reason"]
L --> J
J --> M["Post-apply evaluation
Terraform policy only"]
M -->|"violation"| N["Report error after resources exist"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A secondary;
class B,C,F,H,I,M primary;
class D,E secondary;
class G,K,N danger;
class J ok;
class L warn;
Post-apply evaluation is detection, not prevention
Terraform policy can read values that exist only after the provider acts, such as an assigned ARN or port, but documentation is explicit that apply is not blocked and the violation is surfaced afterwards. A control matrix should label that row detection.
Entitlements decide more deployments than language does. The Free edition includes one policy set of up to five policies; VCS-connected sets and API versions need Standard or Premium, and agent-based evaluation, which also allows runtime pinning for Sentinel, needs Premium with a self-managed agent pool accepting policy jobs. Cost estimates reach Sentinel policy checks but not policy evaluations, which breaks cost rules quietly when a team moves to agents.
One home per rule. The same intent in HCL and in Rego drifts, because they read different shapes — attrs versus resource_changes[].change.after. If you need the rule in CI on a fork without platform access, OPA is the right home; do not enforce a second copy in the platform unless you will change both.
A Check Warning Is Not an Approval Gate
The most expensive governance failure is not a rule that blocks too much. It is a rule everyone believes is blocking while nothing does.
A check block never blocks
The check block runs last, and a failed assertion is only a warning. It runs after Terraform has planned or provisioned the infrastructure, so plan exits zero, CI stays green and the warning scrolls past. The documentation is plain: it is the only validation that does not block. That makes it good for post-apply truth — is the endpoint answering, is encryption actually on — and useless as the control an auditor thinks you have.
If a check must gate, something after it must read the result and fail. The JSON rendering of a plan carries check results, so a CI step can parse them and exit non-zero; the block alone will not.
Scanners fall into the same trap differently. Checkov exits non-zero on failed checks by default, which is a real gate. Adding --soft-fail so a release can proceed converts it to advice, and that is a policy change nobody reviewed. If the flag is permanent the control is gone; if temporary it needs an expiry date.
Policy enforcement carries the same three verbs, and mixing them produces theatre:
Three verbs and a hidden fourth
- Advisory never interrupts the run. Its only output is text in a UI, so use it for migrations and new rules, each with a promotion date.
- Enforced stops the run until the change satisfies the rule.
mandatoryandhard-mandatorylive here, with a CI exit code as the gate. - Override also stops the run, then lets a permissioned person continue. That is an authorization event with an actor, a timestamp and a reason; without a record it is indistinguishable from a bypass.
- Undecided hides between them: a rule whose input was unknown at plan time did not pass. If the platform renders it as a skip, the control is only as good as the least resolvable variable in the estate.
One question tests any rule. If it failed right now, what would stop the apply? If the answer is "a warning in the log", the rule is advisory whatever its enforcement level says. If the answer is "nothing, we override it every week", it is an exception with extra steps and the register should say so.
Staged rollout is legitimate. One rule file as advisory in development, mandatory in production, promoted by a reviewed policy-set version. What is not legitimate is a rule that is advisory everywhere and described as mandatory in the control documentation, because the next reader will rely on it.
Require Tags, Allowed Regions and Safe Exposure
Three rules appear in almost every first policy pack, and each has a failure mode that only shows up after enforcement starts.
| Rule | Where it breaks | What to do |
|---|---|---|
| Required tags | An aws_* resource policy matches every AWS resource, including types whose schema has no tags argument | Tolerate the missing attribute; provider default_tags help only if they reach the planned attributes, so confirm with one terraform show -json before enforcing |
| Allowed regions | A resource rarely carries its own region; it inherits one from the provider configuration, aliases included | Ask the question as a provider policy against the configured region; if the region arrives through an environment variable the policy has nothing to read, so pin it in configuration first |
| Safe exposure | Inline ingress blocks, separate aws_security_group_rule resources and aws_vpc_security_group_ingress_rule with cidr_ipv4 are three shapes for one intent | Handle the shapes you use, and make an unrecognised shape an explicit failure rather than a skip |
Build the pack locally before it blocks anyone. Terraform 1.17.1, tfpolicy 0.5.x and AWS provider 6.72.0, verified on 5 November 2026; the tests mock the provider, so no credentials or account are required.
Expected observation: validate accepts the pack and the test run reports one pass and one expected failure. Flip the flag and the run fails, which proves the tag rule is live rather than decorative.
Failure check: a region rule that never fires usually means the region comes from the environment. A wildcard tag rule that errors instead of failing cleanly is missing the core::try guard. An exposure rule that passes a separate aws_security_group_rule is a coverage gap, not a false negative.
Cost and cleanup: no cloud spend, only CI minutes and authoring time; delete the local policies and tests directories when done.
Messages are part of the control. A useful failure names the rule, the address, what was expected, what was found and the smallest fix; a useless one says "policy failed" and sends the author to a wiki. Group duplicate findings first: four tag violations in one module are one decision.
Estimate Cost and Record Who Owns the Spend
Cost is where governance most often confuses a forecast with a fact.
An estimate prices the resources in a change at list price for a month, using configuration or plan JSON and a pricing service. A billing limit is what the organisation is actually charged: committed discounts, credits, support, tax, data transfer and the resources nobody wrote in Terraform. The estimate shows the shape of the change before it happens; the invoice shows what happened weeks later. Treating the first as the second either blocks harmless changes or misses expensive ones.
Infracost is the common open tool for the estimate. It parses HCL or plan JSON, needs no cloud credentials, and calls a pricing API with a key held in CI. Pin the major version before wiring a gate to its exit code, because the 2.x command surface is not the 1.x one many pipelines still carry — the documentation showed 2.18.2 when checked on 5 November 2026.
Host-native options are narrower than they look. HCP Terraform can show cost estimates in a run, and Sentinel policy checks can read that data, but policy evaluations cannot, so a cost rule must live in a check-based policy set. Cloud budgets — AWS Budgets, Azure Cost Management, GCP budgets — are billing-side controls with hours or days of lag. They are a backstop for a runaway resource, not an approval gate for a pull request.
Usage is the honest part of any estimate. A plan knows an instance type, not its utilisation; it knows a bucket exists, not that it stores eleven terabytes, so without a usage file the estimate is a floor. That is fine when everyone knows it, and dangerous when a reviewer reads €40 and approves a change that will bill €400. Record the assumption file, currency and price date with the number.
Then decide who owns it. A threshold without an owner produces alerts everyone mutes. The useful rule: when the monthly delta exceeds the threshold, the owner of the cost_center tag must approve in the pull request, and that approval is the evidence. That argues for mandatory_overridable with the spend owner as override authority, or advisory plus a required reviewer. Blocking hard on an estimate with a wide error bar teaches teams to edit the usage file until the number passes.
Figure 4 shows the path and the backstop.
Two disciplines keep the numbers honest. Attach each estimate to a specific commit and price date, so disagreement is resolved by re-running rather than arguing. And record the owner, not only the approval: when the invoice lands, "the cost-centre owner approved a €2,400 increase on 12 November" is a fact someone can act on.
Audit an Exception from Request to Expiry
An exception is a decision with a clock. Everything that makes it auditable comes from that framing.
Six fields are non-negotiable. The rule identifier and version pin what is waived. The scope names the resource address or module and the workspace, so a new resource of the same type is still checked. The owner is a team with authority to accept the risk, never an individual who may change jobs. The reason states the constraint clearly enough that a reviewer could disagree. The compensating control says what reduces the risk while the exception is open. The expiry is a date. Add the approver and the UTC approval timestamp, and require the approver to differ from the requester for high-risk rules; without both, the record is a claim rather than evidence.
Store exceptions as exceptions/policy-exceptions.yaml in version control, validate the file in CI, and have the policy match on rule plus address. An expired entry stops matching, so the original finding returns automatically, and the validator fails the build so someone must renew with new evidence or close and fix. Do not rely on a calendar reminder; the person who set it is often the person who left.
Name the states, because most registers collapse them: requested, active, in review, expired, closed. Only "active" permits the override. A register where everything is active is a list, not a control.
Auditors ask four questions, and none is "was there a policy". Which rule, at which version, blocked which artifact? Who had authority to override? What evidence did they have? When did it expire, and what happened then? The answers are the run identifier, the policy result, the commit hash of the exception file and the approver identity. Screenshots fail the third question and cannot be replayed.
Four ways an exception stops being a control
- Scoped to the rule instead of the address, which hides every future resource of that type.
- Owned by a person, which becomes orphaned when they change jobs.
- Renewed on a rolling basis with no new evidence, which is a permanent policy change wearing a date.
- Expiring past the migration it depends on, which is a promise nobody is tracking.
Break-glass is the legitimate fast path. A time-boxed override for an incident, recorded when used, with retrospective approval inside twenty-four hours and a weekly review. The difference between break-glass and a bypass is entirely in the record.
Review a policy decision
Goal: assemble a pack for region, required tags and a cost-review trigger, prove pass, fail and unknown outcomes, then take one exception from request to expiry.
Prerequisites: Terraform 1.17.1, tfpolicy 0.5.x, AWS provider 6.72.0, Infracost CLI 2.18.2, Conftest 0.71.1, verified on 5 November 2026. Use the placeholder-credential provider pattern from the earlier article; no cloud account is needed.
Lab status: design-only. The commands are the acceptance test. Nothing is applied.
Steps:
- Copy the policy file from the code widget above to
policies/guardrails.policy.hcland runtfpolicy validate --policies=policies. - Run
tfpolicy test --policies=policies --tests=tests; confirm one pass and one expected failure. - Build a saved plan for a tagged bucket in
eu-west-1, renderterraform show -json tfplan > plan.json, and runinfracost scan plan.json --json > estimate.json. Record the monthly delta. - Change the region to
us-east-1and dropcost_center; re-plan and expect both rules to fail with their identifiers. - Set the security group CIDR to a value produced by another resource in the same plan, so it is unknown at plan time, and run a Rego check over
after_unknown.cidr_blocks. Expect a denial, not a pass. - Write the record below for the open CIDR; validate it with today's date, then with yesterday's.
Acceptance test: every row in the table must produce the decision shown, and the unknown row must never render as a pass.
| Case | Input | Expected decision | Evidence recorded |
|---|---|---|---|
| Compliant | eu-west-1, three tags, +€40/month | Pass | Rule ids, plan hash, estimate |
| Wrong region | us-east-1 | Fail, mandatory | Rule id, alias, region found |
| Missing tag | No cost_center | Fail, mandatory | Rule id, address, missing key |
| Open ingress | 0.0.0.0/0 on 443 | Fail, overridable | Rule id, CIDR, approver |
| Unknown CIDR | CIDR from a resource in the same plan | Unknown, never pass | Unknown path, reviewer |
| Cost trigger | Delta €2,400/month | Review required | Estimate, price date, owner |
The record is deliberately boring, because boring is what survives an audit.
# exceptions/policy-exceptions.yaml
- id: GOV-EXC-2026-014
rule: GOV-NET-03
rule_version: 3
scope:
address: aws_security_group.public_edge
workspace: prod-edge
owner: platform-network
reason: "Payment callback needs a fixed source range until the vendor publishes its egress list."
compensating_control: "WAF rate limit, ALB access logs, weekly review"
requested_by: "a.novak@example.com"
approved_by: "security-approvers"
approved_at: "2026-11-05T09:14:00Z"
expires: "2026-12-05"
review_on: "2026-11-26"
ticket: SEC-4412
Expected observation: the pack passes and fails for the reasons in the table, the unknown case never reports success, and the validator accepts the record until the expiry date passes, then fails with rule, address and owner in the message.
Failure check: a green unknown case means the Rego iterates after without reading after_unknown. A validator that accepts yesterday is comparing strings or ignoring time zones. A cost trigger that fires on every change is reading the total, not the delta.
- Cost: no cloud spend; runner minutes, pricing API calls and review time.
- Cleanup: delete
tfplan,plan.json,estimate.jsonand.terraform/; if you adapted this to a real account, destroy and confirm the rule is gone.
The register turns policy from an obstacle into a managed risk position. When a reviewer can see every open exception, its owner, its remaining days and its compensating control, the conversation stops being about whether the gate is too strict and becomes about which risks the organisation is choosing to carry.
Next in the Series
In Scale the Repository Without Creating One Giant State, we'll explore Choose root modules, repositories and state boundaries around trust, ownership and change cadence.