8.2.1. Policy Enforcement with Sentinel and OPA
💡 First Principle: Policy-as-code evaluates a plan against codified rules before apply, so organizational requirements (cost caps, required tags, approved resource types) are enforced automatically and consistently rather than relied on through human review.
HCP Terraform enforces policy as code between plan and apply using one of two engines: Sentinel (HashiCorp's policy language) or OPA (Open Policy Agent, using the Rego language). Policies are grouped into policy sets and attached to workspaces or projects. They can check things like "every resource has a cost-center tag," "no public S3 buckets," or "monthly cost stays under a threshold."
Policies have enforcement levels that determine what a failure does:
| Enforcement level | Effect on a failing policy |
|---|---|
| Advisory | Logs a warning; the run proceeds |
| Soft-mandatory | Blocks the run, but an authorized user can override |
| Hard-mandatory | Blocks the run; no override allowed |
⚠️ Exam Trap: Two facts: (1) policy enforcement is an HCP Terraform/Enterprise feature, not part of the community CLI; (2) Sentinel and OPA are alternative engines you choose between. Also know the enforcement levels — hard-mandatory cannot be overridden, soft-mandatory can be by an authorized user.
Reflection Question: Why would an organization choose soft-mandatory rather than hard-mandatory for a cost-limit policy?