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 filled 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. Organizations running OPA in CI/CD pipelines consistently report substantial reductions in policy violations reaching production, because enforcement happens at deploy time rather than discovery time.
Policy-as-Code is the practice of writing security and compliance policies as executable code evaluated automatically during infrastructure provisioning. GRC teams currently spend an average of 14 hours per week on manual compliance processes (Drata, State of GRC 2025), and a significant portion of that time goes toward monitoring for and remediating policy violations that never would have reached production under automated enforcement. 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?
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. The violations are not rare. They persist for weeks, undetected, because no mechanism exists to catch them between audits.
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 typical auditor expectations for control testing without manual screenshot collection. For SOC 2 Common Criteria CC4.1 and NIST CSF 2.0 controls, policy-as-code evaluations serve as direct evidence of control operating effectiveness.
The audit fix. 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. Graduated by the Cloud Native Computing Foundation (CNCF) on January 29, 2021, OPA provides a general-purpose, vendor-neutral policy engine evaluating 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.
The audit fix. 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
Terraform Sentinel is HashiCorp’s embedded policy-as-code framework for Terraform Cloud and Terraform Enterprise. For GRC teams spending 14 hours per week on manual compliance processes (Drata, State of GRC 2025), Sentinel’s native integration eliminates a significant portion of the evidence collection and violation tracking overhead. 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 at developer.hashicorp.com/sentinel).
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.
The audit fix. 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?
Compliance requirements across frameworks have grown more granular and technically specific over recent years, driven by SEC cybersecurity disclosure rules, PCI DSS 4.0, and the CMMC program’s enforcement expansion. GRC Engineering teams implementing policy-as-code address this pressure through 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.
In practice, auditors commonly look for exception documentation as part of their change management and access control testing. Policy-as-code systems with codified exceptions provide stronger evidence than 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 can satisfy multiple framework controls simultaneously. For example, an encryption-at-rest enforcement rule addresses SOC 2 CC6.1 (logical access controls), ISO/IEC 27001:2022 A.8.24 (Use of cryptography), HIPAA 164.312(a)(2)(iv) (Encryption and decryption, addressable), and PCI DSS 4.0 Requirements 3.5 and 3.6 (protection of stored account data and key management). The policy library maps each rule to its applicable framework controls, and evidence generated from a single evaluation satisfies all mapped requirements.
The audit fix. 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. Manual enforcement typically produces persistent low-severity violations that survive across multiple sprint cycles before anyone notices. 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 (January 29, 2021), vendor-neutral, open-source policy engine working across Kubernetes, Terraform, CI/CD pipelines, and applications. 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, compressing audit preparation by automating evidence generation across the audit period rather than reconstructing it at the end. 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. The magnitude of efficiency improvement depends on framework scope and starting maturity.
What programming language do OPA policies use?
OPA policies use Rego, a purpose-built declarative query language developed alongside OPA and maintained by the OPA project, which graduated from CNCF on January 29, 2021. Rego describes the desired compliance state rather than the evaluation procedure, making policies readable by compliance analysts and auditors alongside engineers. Rego supports 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. 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. 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.
Subscribe to The Authority Brief for next week’s analysis.