The Slack message arrived at 4:47 PM on a Thursday: “Hey, the staging database needs public access for the demo tomorrow. I added a security group exception. Can you approve?” The engineer had already pushed the change. The compliance team discovered it three months later during the SOC 2 evidence review. The exception was still live. The database had been publicly accessible for 92 days.
This failure did not stem from negligence or incompetence. The password policy existed. The network segmentation standard was documented. The access control requirements were clearly written in a 47-page security policy PDF stored in SharePoint. The problem: none of these policies had enforcement mechanisms. Policies without enforcement are suggestions, and suggestions do not survive a Thursday afternoon deadline.
Policy-as-Code eliminates the gap between written policy and operational enforcement by expressing security requirements as executable code. Open Policy Agent (OPA) and Terraform Sentinel are the two dominant tools for this practice. The implementation patterns, tooling decisions, and deployment strategies below cover what teams need to convert compliance policies from documents into infrastructure guardrails.
Policy-as-Code is the practice of writing security and compliance policies as executable code evaluated automatically during infrastructure provisioning. Organizations with manual policy enforcement experience an average of 23 policy violations per quarter per cloud account, with 40% persisting more than 30 days [HashiCorp State of Cloud Strategy 2024]. Using Open Policy Agent (OPA) with Rego or Terraform Sentinel, organizations enforce policies at deployment time, blocking non-compliant changes before they reach production and generating audit evidence as a byproduct of enforcement.
Why Do Written Policies Fail Without Code Enforcement?
Organizations with manual policy enforcement average 23 policy violations per quarter per cloud account, with 40% persisting more than 30 days before detection [HashiCorp State of Cloud Strategy 2024]. Every compliance program begins with written policies. Access control policies define who gets access to production systems. Encryption policies mandate data protection at rest and in transit. Change management policies require peer review before deployment. These documents satisfy auditors during the policy review phase of an engagement.
The Enforcement Gap
The problem emerges between audit cycles. Written policies depend on human compliance: engineers reading the policy, remembering the requirements, and applying them correctly under deadline pressure. Research from HashiCorp shows organizations with manual policy enforcement experience an average of 23 policy violations per quarter per cloud account, with 40% of violations persisting for more than 30 days before detection [HashiCorp State of Cloud Strategy 2024].
Policy-as-Code closes this gap by making violations technically impossible. The policy rule evaluates every infrastructure change before provisioning. Non-compliant changes fail automatically. The engineer receives immediate feedback identifying the violation and the specific policy requirement, and the violation never reaches production.
The Audit Evidence Advantage
Every policy evaluation generates a structured log entry: timestamp, actor, resource, policy rule, and pass/fail result. This evidence stream satisfies auditor requirements for control testing without manual screenshot collection. For SOC 2 Common Criteria and NIST CSF 2.0 controls, policy-as-code evaluations serve as direct evidence of control operating effectiveness.
Pull your most recent SOC 2 or ISO 27001 audit report. Count the number of controls where evidence consisted of screenshots, manual exports, or verbal attestations. Each one represents a policy enforcement gap where a code-based rule would provide continuous, automated evidence. Prioritize the three controls with the most audit exceptions for policy-as-code implementation.
Open Policy Agent: The Vendor-Neutral Standard
Open Policy Agent (OPA) is the most widely adopted policy engine in the cloud-native ecosystem, graduating from the Cloud Native Computing Foundation (CNCF) in February 2021 [CNCF 2021]. Graduated by the Cloud Native Computing Foundation (CNCF) in February 2021, OPA provides a general-purpose policy engine decoupled from any specific infrastructure platform [CNCF 2021]. OPA evaluates structured data (JSON, YAML, HCL) against policies written in Rego, a purpose-built declarative language.
How Rego Works
Rego is a declarative query language designed for policy decisions. Unlike imperative languages (Python, Go), Rego policies describe the desired state rather than the evaluation procedure. A Rego rule for encryption enforcement reads as a declaration: “deny if any database resource lacks encryption at rest.” OPA evaluates every resource in the input data against this declaration and returns a pass or deny decision.
The declarative model matters for compliance teams. Policy rules written in Rego are readable by auditors and compliance analysts, not only by engineers. The translation from written policy to Rego rule follows a direct mapping: the English policy statement becomes the Rego rule logic, and both artifacts live side-by-side in version control.
OPA Integration Points
OPA integrates at four primary points in the infrastructure and application lifecycle:
| Integration Point | Tool | Use Case |
|---|---|---|
| CI/CD Pipeline | Conftest | Evaluate Terraform plans, Dockerfiles, Kubernetes manifests against policies before deployment |
| Kubernetes Admission | Gatekeeper | Block non-compliant pods, deployments, and services at the cluster admission controller |
| API Gateway | OPA Envoy Plugin | Enforce authorization policies on API requests in real time |
| Application Layer | OPA SDKs | Embed policy decisions directly into application logic for fine-grained access control |
The CI/CD integration through Conftest delivers the fastest compliance value. Conftest evaluates infrastructure-as-code artifacts against OPA policies during the pull request review process. Non-compliant infrastructure changes fail the CI pipeline and never reach the deployment stage.
Install Conftest in your CI/CD pipeline and write one Rego policy enforcing a requirement from your highest-priority compliance framework. Start with a binary enforcement: “all S3 buckets must have versioning enabled” or “all RDS instances must use encryption at rest.” Run the policy against your current Terraform codebase to identify existing violations before enabling enforcement.
Terraform Sentinel: The HashiCorp-Native Approach
With organizations spending 40-60 hours of engineering time per framework on manual compliance [CyberSierra 2026], Terraform Sentinel offers HashiCorp’s embedded policy-as-code framework for Terraform Cloud and Terraform Enterprise. Sentinel policies evaluate between the terraform plan and terraform apply phases, inspecting the planned infrastructure changes and blocking any execution violating organizational rules [HashiCorp Sentinel Documentation].
Sentinel vs. OPA: The Selection Decision
The choice between Sentinel and OPA depends on three factors: infrastructure-as-code tooling, organizational scale, and multi-platform requirements.
| Factor | Choose Sentinel | Choose OPA |
|---|---|---|
| IaC Platform | Terraform Cloud/Enterprise exclusively | Multi-tool (Terraform, Kubernetes, CloudFormation) |
| Policy Scope | Infrastructure provisioning only | Infrastructure, Kubernetes, APIs, applications |
| Licensing | HashiCorp commercial license | Open source (Apache 2.0) |
Organizations using Terraform Cloud or Enterprise as their sole IaC platform benefit from Sentinel’s native integration. The policy evaluation is automatic, requiring no additional CI/CD configuration. Organizations running Kubernetes alongside Terraform, or using multiple IaC tools, benefit from OPA’s platform-neutral architecture.
Writing Effective Sentinel Policies
Sentinel policies follow a three-part structure: import the Terraform plan data, filter resources by type, and evaluate each resource against the compliance requirement. Effective policies include descriptive error messages explaining the violation and referencing the specific compliance control.
The enforcement level determines the policy behavior. Advisory policies log violations without blocking. Soft-mandatory policies allow authorized overrides with documented justification. Hard-mandatory policies block all violations without exception. Start every new policy at the advisory level and promote to soft-mandatory after two weeks of evaluation data.
If your organization uses Terraform Cloud or Enterprise, enable the Sentinel integration and deploy three policies in advisory mode this week. Recommended starting policies: (1) mandatory resource tagging for cost allocation and ownership tracking, (2) encryption at rest enforcement for all storage and database resources, and (3) public access blocking for all storage buckets and database instances. Review advisory violations for two weeks before promoting to soft-mandatory enforcement.
How Should Compliance Teams Implement Policy-as-Code?
With 85% of executives reporting compliance requirements increased in difficulty [Security Boulevard 2026], GRC Engineering teams implementing policy-as-code follow a consistent deployment pattern. The pattern applies regardless of whether the organization uses OPA, Sentinel, or cloud-native policy tools.
Pattern 1: The Policy Translation Workflow
Each written policy translates to code through a four-step workflow:
- Decompose: Break the policy document into individual, testable requirements. A single access control policy often contains 8 to 12 discrete requirements.
- Codify: Write each requirement as a machine-readable rule in Rego or Sentinel. One requirement equals one rule.
- Test: Write test cases for each rule covering both compliant and non-compliant inputs. Policy rules need the same test coverage as application code.
- Deploy: Release in advisory mode, evaluate results, then promote to enforcement.
Pattern 2: The Exception Management System
Every policy needs an exception mechanism. The exception system documents the business justification, the approving authority, the expiration date, and the compensating controls in place during the exception period. Store exceptions as code alongside the policy rules: a JSON or YAML allowlist referenced by the policy evaluation logic.
Auditors expect exception documentation. Policy-as-code systems with codified exceptions provide superior evidence compared to email-chain approvals. The exception, its justification, and its approval live in version control with a complete audit trail of who approved the exception, when, and for how long.
Pattern 3: The Policy Library Architecture
Mature organizations maintain a centralized policy library: a version-controlled repository containing all policy-as-code rules, organized by compliance framework and control family. The library serves as the single source of truth for policy enforcement across all infrastructure pipelines. Changes to policy rules follow the same code review process as application code changes.
This architecture supports multi-framework compliance. A single encryption policy rule satisfies SOC 2 CC6.1, ISO 27001 A.10.1, HIPAA 164.312(a)(2)(iv), and PCI DSS 3.4 simultaneously. The policy library maps each rule to its applicable framework controls, and evidence generated from a single evaluation satisfies all mapped requirements.
Create a dedicated Git repository for your organization’s policy-as-code library. Structure the repository by compliance framework (SOC 2, ISO 27001, HIPAA) with subdirectories for each control family. Add a mapping file linking each policy rule to its corresponding framework control numbers. This repository becomes the auditable source of truth for your compliance-as-code program and the foundation for your GRC Engineering maturity progression.
Policy-as-Code is the enforcement layer of GRC Engineering. Written policies without code enforcement are suggestions. Code enforcement without written policies is undocumented automation. The practice works when both artifacts exist together: the human-readable policy for governance, the machine-executable rule for enforcement, and the version control history for audit evidence. Organizations running both OPA and documented policies already have the architecture. The remaining work is connecting them.
Frequently Asked Questions
What is policy-as-code?
Policy-as-Code is the practice of expressing security, compliance, and operational policies as machine-readable code evaluated automatically during infrastructure provisioning, reducing the average 23 policy violations per quarter that manual enforcement produces [HashiCorp State of Cloud Strategy 2024]. The policies enforce requirements at deployment time, blocking non-compliant changes before they reach production and generating audit evidence from every evaluation decision.
What is the difference between OPA and Terraform Sentinel?
OPA (Open Policy Agent) is a CNCF-graduated (February 2021), vendor-neutral, open-source policy engine working across Kubernetes, Terraform, CI/CD pipelines, and applications [CNCF 2021]. Terraform Sentinel is HashiCorp’s proprietary policy framework embedded exclusively in Terraform Cloud and Enterprise. Choose OPA for multi-platform policy enforcement and Sentinel for Terraform-only environments with native integration requirements.
How does policy-as-code help with SOC 2 compliance?
Policy-as-Code provides continuous evidence of control operating effectiveness for SOC 2 audits, cutting audit preparation from 4-6 weeks to 1-2 weeks by eliminating manual evidence collection [CyberSierra 2026]. Every policy evaluation generates a structured log entry (timestamp, actor, resource, result) serving as direct evidence for Common Criteria controls. Auditors receive automated evidence of policy enforcement rather than point-in-time screenshots, strengthening the control narrative and reducing the risk of audit exceptions.
What programming language do OPA policies use?
OPA policies use Rego, a purpose-built declarative query language developed alongside OPA and maintained by the CNCF-graduated project since 2021. Rego describes the desired compliance state rather than the evaluation procedure, making policies readable by compliance analysts and auditors alongside engineers. Rego supports complex logic including nested data evaluation, partial rule definition, and incremental evaluation across large datasets.
How long does policy-as-code implementation take?
A focused implementation delivers the first five enforced policies within four weeks: one week for tool selection and pipeline integration, one week for policy translation and testing, and two weeks in advisory mode before activating enforcement. Expanding the policy library to cover a full compliance framework takes an additional 8 to 12 weeks depending on the number of controls in scope.
Does policy-as-code work with multi-cloud environments?
OPA works natively across AWS, Azure, GCP, and Kubernetes environments, evaluating structured data regardless of source platform and enforcing consistent policies across all providers [CNCF 2021]. A single OPA policy preventing public storage access applies to S3 buckets, Azure Blob Storage, and GCP Cloud Storage with provider-specific input adapters. Sentinel is limited to Terraform-managed resources but supports any cloud provider Terraform provisions.
How do organizations handle policy exceptions in code?
Policy exceptions are stored as structured data (JSON or YAML allowlists) alongside the policy rules in version control, with each exception documenting the business justification, approving authority, and expiration date for full audit traceability. Each exception includes the business justification, approving authority, expiration date, and compensating controls. The policy evaluation logic references the exception list and logs both the exception and its documented justification in the audit trail, providing auditors with complete exception documentation.
Get The Authority Brief
Weekly compliance intelligence for security leaders and technology executives. Frameworks decoded. Audit strategies explained. Regulatory updates analyzed.