Policy as Code: Guardrails and Compliance with OPA and Sentinel
Evaluate infrastructure rules with OPA, HashiCorp Sentinel, and AWS controls, and understand how integrations enforce policy results.
Policy as Code lets teams evaluate infrastructure against explicit rules at selected workflow stages. This guide scopes its examples to OPA v1.22.4 with Rego v1 and Terraform CLI 1.17.x, explains how integrations choose enforcement behavior, and shows how one control can be linked to a policy check, retained evidence, and an accountable owner.
Policy as Code: Guardrails and Compliance with OPA and Sentinel
Policy as code puts explicit checks into infrastructure workflows. A policy can reject a Terraform plan that violates a rule, but passing a policy does not establish that a system complies with a standard; coverage, exceptions, runtime enforcement, and evidence still matter.
Common options include Open Policy Agent (OPA), HashiCorp Sentinel, and AWS controls such as IAM policies and Service Control Policies. They run at different points in a workflow and use different policy languages.
Introduction
You write rules that describe acceptable infrastructure, then run them against a configuration or plan. The integration decides what a failed policy means: a warning, a blocked run, or an override path.
Policies can enforce anything you can express programmatically. Common use cases include requiring encryption at rest, enforcing naming conventions, restricting which regions resources can be deployed to, ensuring cost controls like budget alerts exist, and preventing public exposure of sensitive resources.
Automated checks can catch specified conditions before deployment. They do not replace review of risks that the policy does not cover.
The examples below use OPA v1.22.4 with Rego v1 syntax, Terraform CLI v1.17.2 (in the 1.17.x line), and Sentinel runtime 0.41.0 for the Sentinel comparison. These versions are separate: integrations can package or pin different runtimes. Check the version configured by the integration you deploy. See the OPA v1.22.4 release, Rego v1 language reference, Sentinel runtime changelog, and Terraform CLI documentation for 1.17.x.
When to Use / When Not to Use
When policy as code makes sense
Policy as code can help when misconfiguration is costly, especially when a check runs before the affected resource is deployed. It only catches conditions the policy expresses and the evaluation input exposes.
Use it when you have multiple teams deploying infrastructure independently. Without automated policy checks, each team might interpret standards differently. A policy library enforced in CI creates consistency without requiring a central approver for every change.
Policy evaluation logs can show that a particular check ran against a particular input. They are one piece of control evidence, not proof that a regulatory framework is satisfied; record the check’s scope, version, exceptions, and accountable owner too.
When to skip it
Policy as code only makes sense when compliance failures carry real cost. If you’re running a handful of resources with one or two people who know the system, writing policies is overhead you don’t need. A code review from someone familiar with the codebase catches misconfigurations just as well, without the added friction of automated checks.
This gets at the real question: how fast is your change velocity? If every infrastructure change gets genuine human attention, policy as code is optional. If your team is still experimenting with naming conventions, tagging strategies, or resource architecture, premature policy enforcement locks in decisions before the team has settled on what good looks like. You end up spending engineering cycles updating policies as standards evolve instead of building the actual infrastructure.
In a regulated environment, a small team may still need evidence that a particular control ran before deployment. A policy result can be one evidence item; the team still needs to define the control’s scope, retain the relevant input and result, document exceptions, and assign an owner.
When misconfiguration costs are low and your team is small, manual review works fine. When those costs climb or your team grows past the point where everyone sees every change, automated enforcement becomes worth the investment.
OPA Rego Language Basics
OPA evaluates policies written in Rego. Rego is declarative: rules describe which inputs satisfy a condition. The snippets here target Rego v1 and OPA v1.22.4; other OPA integrations may bundle a different engine version.
package terraform.analysis
import rego.v1
# Deny S3 buckets without encryption
deny_s3_unencrypted if {
some rc in input.resource_changes
rc.type == "aws_s3_bucket"
rc.change.after != null
not has_encryption_config(rc.change.after)
}
has_encryption_config(after) if {
configurations := object.get(after, "server_side_encryption_configuration", [])
is_array(configurations)
some configuration in configurations
is_object(configuration)
rules := object.get(configuration, "rule", [])
is_array(rules)
some rule in rules
is_object(rule)
defaults := object.get(rule, "apply_server_side_encryption_by_default", [])
is_array(defaults)
some encryption in defaults
is_object(encryption)
algorithm := object.get(encryption, "sse_algorithm", "")
algorithm in {"AES256", "aws:kms", "aws:kms:dsse"}
}
# Deny EC2 instances without tags
deny_ec2_missing_tags if {
some rc in input.resource_changes
rc.type == "aws_instance"
rc.change.after != null
not rc.change.after.tags
}
# Deny RDS instances that are publicly accessible
deny_rds_public_access if {
some rc in input.resource_changes
rc.type == "aws_db_instance"
rc.change.after != null
rc.change.after.publicly_accessible == true
}
Rego policies operate on input documents. For Terraform, the input is a JSON representation of the plan or state. You write rules that traverse this document and return violations when conditions are met.
The deny prefix is convention—OPA does not require it. You can name your rules anything. The important part is that when a rule evaluates to true, that represents a violation.
Writing and Testing Policies
OPA ships with a testing framework that makes policy development iterative rather than trial-and-error.
package terraform.analysis
import rego.v1
# Require a nested rule with a recognized default-encryption algorithm.
has_encryption_config(after) if {
configurations := object.get(after, "server_side_encryption_configuration", [])
is_array(configurations)
some configuration in configurations
is_object(configuration)
rules := object.get(configuration, "rule", [])
is_array(rules)
some rule in rules
is_object(rule)
defaults := object.get(rule, "apply_server_side_encryption_by_default", [])
is_array(defaults)
some encryption in defaults
is_object(encryption)
algorithm := object.get(encryption, "sse_algorithm", "")
algorithm in {"AES256", "aws:kms", "aws:kms:dsse"}
}
# The external data document maps resource addresses to approved tickets.
approved_exception(rc) if {
rc.address == "aws_s3_bucket.legacy_archive"
data.exceptions[rc.address].ticket == "SEC-1234"
}
deny contains rc.address if {
some rc in input.resource_changes
rc.type == "aws_s3_bucket"
rc.change.after != null
not has_encryption_config(rc.change.after)
not approved_exception(rc)
}
allow if not deny[_]
test_allow_encrypted_bucket if {
allow with input as {
"resource_changes": [{
"address": "aws_s3_bucket.logs",
"type": "aws_s3_bucket",
"change": {
"after": {
"server_side_encryption_configuration": [{
"rule": [{
"apply_server_side_encryption_by_default": [{
"sse_algorithm": "AES256"
}]
}]
}]
}
}
}]
}
}
test_deny_empty_encryption_rule if {
not allow with input as {
"resource_changes": [{
"address": "aws_s3_bucket.logs",
"type": "aws_s3_bucket",
"change": {
"after": {
"server_side_encryption_configuration": [{"rule": []}]
}
}
}]
}
}
test_deny_missing_encryption_algorithm if {
not allow with input as {
"resource_changes": [{
"address": "aws_s3_bucket.logs",
"type": "aws_s3_bucket",
"change": {
"after": {
"server_side_encryption_configuration": [{
"rule": [{
"apply_server_side_encryption_by_default": [{}]
}]
}]
}
}
}]
}
}
test_deny_unencrypted_bucket if {
not allow with input as {
"resource_changes": [{
"address": "aws_s3_bucket.logs",
"type": "aws_s3_bucket",
"change": {"after": {}}
}]
}
}
test_allow_ticketed_exception if {
allow with input as {
"resource_changes": [{
"address": "aws_s3_bucket.legacy_archive",
"type": "aws_s3_bucket",
"change": {"after": {}}
}]
} with data.exceptions as {
"aws_s3_bucket.legacy_archive": {"ticket": "SEC-1234"}
}
}
The tests cover a valid encrypted bucket, missing or incomplete encryption settings, an unencrypted bucket, and a ticketed exception. The fixtures use Terraform plan JSON under input.resource_changes and an exceptions.json document loaded as data.exceptions. Check the exact plan shape produced by your provider; a test fixture should match the plan your pinned toolchain generates.
For example, policies/exceptions.json can contain:
{
"aws_s3_bucket.legacy_archive": { "ticket": "SEC-1234" }
}
Run the suite with the pinned OPA binary:
./opa test ./policies/ -v
Integrating with CI/CD Pipelines
The real value of policy as code emerges in automated pipelines. Every infrastructure change gets evaluated against policies before deployment proceeds.
# GitHub Actions example
name: Terraform Policy Check
on:
pull_request:
paths:
- "**.tf"
- "policies/**"
jobs:
OPA:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.17.2
- name: Install OPA v1.22.4
run: |
curl -L -o opa https://openpolicyagent.org/downloads/v1.22.4/opa_linux_amd64_static
chmod +x opa
- name: Test policies
run: ./opa test ./policies/ -v
- name: Run Terraform plan
run: |
terraform init
terraform plan -out=plan.tfplan
terraform show -json plan.tfplan > plan.json
- name: Evaluate policies
run: |
./opa eval --fail-defined --data policies/ --input plan.json \
'data.terraform.analysis.deny[_]'
The example pins Terraform CLI to 1.17.2 and OPA to 1.22.4. --input supplies Terraform’s JSON plan; --data loads Rego modules and the exceptions.json data file. The query selects individual denial entries, so --fail-defined returns a non-zero status for a denial or evaluation error. The CI runner then blocks the step. This is CI’s enforcement choice, not a behavior shared by every OPA integration.
Terraform Validation with OPA
Beyond CI/CD integration, OPA can validate Terraform code directly without applying changes. This is useful for pre-merge checks that do not require running an actual plan.
Conftest evaluates policies against configuration files without requiring a Terraform plan. It is a separate integration with its own release and embedded OPA dependency; the Conftest v0.55.0 example below does not inherit the OPA v1.22.4 pin or promise Rego v1 compatibility. Check the versions supported by the particular Conftest release before reusing a policy module.
# .github/workflows/tf-validation.yml
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install conftest
run: |
curl -L -o conftest.tar.gz https://github.com/open-policy-agent/conftest/releases/download/v0.55.0/conftest_0.55.0_Linux_x86_64.tar.gz
tar xzf conftest.tar.gz
- name: Validate Terraform
run: |
conftest test . --policy policy.rego
HCP Terraform supports OPA policy sets and Sentinel policies as separate integrations. Sentinel has its own language and runtime; porting a policy means translating its logic and tests, not reusing Rego syntax. Check the runtime version configured for the specific policy set or product.
Real-World Policy Examples
Budget enforcement policies prevent runaway infrastructure costs.
package terraform.analysis
import rego.v1
has_cost_alert if {
some rc in input.resource_changes
rc.type == "aws_budgets_cost_notification"
rc.change.after != null
rc.change.after.notification != null
}
deny_missing_cost_alert if {
not has_cost_alert
}
deny_unlimited_budget if {
some rc in input.resource_changes
rc.type == "aws_budgets_cost_notification"
rc.change.after != null
rc.change.after.budget_type == "USAGE"
}
Tagging policies enforce organizational naming standards.
package terraform.analysis
import rego.v1
required_tags := {"Environment", "Team", "CostCenter", "Application"}
deny_missing_required_tags if {
some rc in input.resource_changes
is_compute_resource(rc.type)
missing_tags := required_tags - get_tags(rc)
count(missing_tags) > 0
}
is_compute_resource(resource_type) if {
resource_type == "aws_instance"
}
is_compute_resource(resource_type) if {
resource_type == "aws_ecs_service"
}
get_tags(rc) := tags if {
tags := {k | rc.change.after.tags[k]}
}
Network policies prevent accidental public exposure.
package terraform.analysis
deny_public_rds if {
some rc in input.resource_changes
rc.type == "aws_db_instance"
rc.change.after.publicly_accessible == true
}
deny_public_load_balancer if {
some rc in input.resource_changes
rc.type == "aws_lb"
rc.change.after.scheme == "internet-facing"
not has_waf_access_logging(rc)
}
OPA vs Sentinel vs AWS Policy Comparison
| Aspect | OPA | Sentinel | AWS controls |
|---|---|---|---|
| Version in examples | OPA v1.22.4 / Rego v1 | Runtime 0.41.0; integrations may pin another | AWS service versions vary |
| Scope | Engine used by integrations that call it | HashiCorp products with Sentinel integration | AWS services |
| Language | Rego | Sentinel | IAM JSON and service-specific formats |
| Testing | opa test |
Sentinel test framework | IAM Access Analyzer and service tooling |
| Enforcement | Caller or integration sets behavior | Integrating product sets enforcement level | Target service applies its rules |
Policy Enforcement Flow
flowchart TD
A[Terraform plan] --> B[CI calls OPA]
B --> C{Decision and evaluation status}
C -->|No denial, no error| D[Required CI status passes]
C -->|Denial or evaluation error| E[Required CI status fails]
E --> F[Review result and fix or approve exception]
F --> A
D --> G[Apply through deployment workflow]
G --> H[State updated]
The diagram shows the decision path, not an OPA guarantee. OPA evaluates a query; the caller decides whether to stop a run. In a CI gate, fail the step on a denial or evaluation error. For a service calling OPA’s API, the service also chooses fail-open (allow if OPA cannot answer) or fail-closed (deny if it cannot answer). That outage choice is separate from the policy’s allow/deny result. See the OPA operations guide.
HCP Terraform has platform-specific enforcement settings: OPA policies can be advisory or mandatory; Sentinel policies can be advisory, soft-mandatory, or hard-mandatory. Overrides depend on the policy-set configuration and user permissions. Sentinel runtime 0.41.0 is a reference version here, not a promise that every HCP Terraform or other integration runs it. Check the HCP Terraform policy enforcement guide for the target integration.
Here is one example of mapping an internal control to a check, evidence, and owner. It is an evidence plan for that control, not a claim of framework-wide compliance.
| Internal control | Policy check | Evidence to retain | Accountable owner |
|---|---|---|---|
SEC-STOR-004: new or changed S3 buckets must have a server-side encryption configuration |
Run the OPA denial query against Terraform 1.17.2 plan JSON as a required CI status | Plan JSON, OPA version, policy commit, test and evaluation output, CI run ID, and any approved exception ticket | Cloud Security control owner |
Trade-off Analysis
Policy Engine Selection
| Factor | OPA | Sentinel | AWS controls |
|---|---|---|---|
| Cost | Open-source engine; hosting and integration vary | Depends on HashiCorp product plan | Depends on AWS service |
| Language | Rego | Sentinel | IAM JSON or service-specific formats |
| Policy reuse | Packages and bundles | Modules | Service-specific policies |
| Evaluation point | Where an integration calls the engine | Where a product provides Sentinel integration | Where the AWS service evaluates the policy |
| Enforcement | Caller or integration sets behavior | Integrating product sets enforcement level | Target service applies its documented rules |
OPA Rego Complexity vs Simplicity
Simple policies (allow/deny) are straightforward to write and maintain. The deny_s3_unencrypted pattern—checking a single attribute and returning true if violated—is easy to read and debug.
Complex policies (exceptions, conditions, multi-resource) require careful Rego design. Using helper functions and separating data transformation from logic evaluation keeps policies readable. Writing all logic inline makes policies impossible to test in isolation.
The tradeoff is between brevity and maintainability. Inline policies are shorter but harder to test. Helper functions add indirection but enable unit testing of individual logical components.
A simple policy that checks a single condition looks like this:
package policy.s3
import rego.v1
# This small example expects normalized input: input.buckets is an array.
deny contains bucket.name if {
some bucket in input.buckets
bucket.encrypted == false
}
allow if not deny[_]
The rule returns the names of unencrypted buckets from this normalized input. The tested Terraform plan example above uses input.resource_changes and an exception document instead; do not mix the two input shapes.
A complex policy that enforces multiple tags across resource types benefits from helper functions:
package policy.tags
import rego.v1
required_tags := {"environment", "cost-center", "owner"}
has_required_tags(tags) if {
every tag in required_tags {
object.get(tags, tag, "") != ""
}
}
deny contains resource.name if {
some resource in input.resources
tags := object.get(resource, "tags", {})
not has_required_tags(tags)
}
This example expects normalized resources with a tags object. The helper keeps the tag requirement in one place, while the denial rule handles resource selection.
Testing follows the same split. Simple policies use a single test case per rule:
package policy.s3
import rego.v1
test_deny_unencrypted_bucket if {
denials := deny with input as {"buckets": [{"name": "legacy", "encrypted": false}]}
"legacy" in denials
}
Complex policies test each helper function with multiple cases:
package policy.tags
import rego.v1
test_has_required_tags_all_present if {
has_required_tags({"environment": "prod", "cost-center": "core", "owner": "platform"})
}
test_has_required_tags_missing_one if {
not has_required_tags({"environment": "prod", "owner": "platform"})
}
Extract a helper when a condition is repeated or the input traversal becomes difficult to review. Keep the input shape and tests close to the policy so future edits can be checked against the same assumptions.
Performance matters when Rego evaluates large plan files. Every input.resource[_] traversal scans the entire resource graph. A policy with three or four broad traversals on a plan with 500 resources can take seconds to evaluate. Profile with opa eval --explain perf to identify slow traversals. Push predicates down into rule conditions early—Rego evaluates from left to right and stops on the first failure in a conjunction:
# Slow: scans all resources before checking encryption
deny_s3_unencrypted if {
input.resource.aws_s3_bucket.anyBucket
not input.resource.aws_s3_bucket.anyBucket.server_side_encryption_configuration
}
# Faster: check encryption first, only then look up the bucket
deny_s3_unencrypted if {
some bucket in input.resource.aws_s3_bucket
not bucket.server_side_encryption_configuration
}
The second form binds bucket only when the negation would succeed, avoiding an unnecessary full-graph scan.
Policy Scope Decisions
Global policies (applied to every resource) catch everything but generate noise when teams have legitimate exceptions. A global “all resources must have cost center tag” creates violations for resources that genuinely cannot have tags.
Resource-type policies target specific risky resources. “Deny S3 buckets without encryption” and “Deny RDS instances publicly accessible” focus on high-impact cases without flagging every untagged resource.
Exception-based policies start with a deny and add exceptions for known legitimate cases. This approach works well but requires maintenance—every legitimate exception becomes a permanent exception unless someone periodically reviews them.
For most organizations, resource-type policies with specific targeting strike the right balance between coverage and noise.
Choosing a policy scope follows a simple heuristic: start with the risk, not the rule. Ask what the worst case is if a resource violates the policy. If the worst case is a data breach or a compliance failure, write a resource-type policy targeting only that resource. If the worst case is cost leakage or operational confusion, a broader scope may be justified—but narrow it to the specific resource category that generates the cost.
Global policies make sense only for a small set of non-negotiable baselines: no public S3 access, no unencrypted databases, no resource that bypasses your tagging taxonomy entirely. Even then, global policies should be combined with resource-type policies for the resources that matter most. A global “tag everything” policy with a resource-type override for “S3 buckets must have encryption” gives you coverage without flagging every untagged resource that genuinely cannot carry a tag.
Exception-based policies are useful when you have a known legitimate case that cannot be remediated immediately. The pattern is common in migrations: you cannot encrypt the legacy bucket until the application team finishes their migration, so you add an exception and set a calendar reminder. The problem is that exceptions accumulate. Every quarter you should audit your exception list and remove the ones that are no longer current. If an exception has been in place for more than 90 days without a remediation plan, it is time to escalate or close it.
A practical approach for most teams: start with resource-type policies targeting your highest-risk resources (S3, RDS, IAM roles). Add a global baseline policy only for the three or four rules that apply universally. Review the global policy’s violation output after 30 days—if it is flagging more than 20% of resources, the scope is too broad and needs narrowing.
Policy Evaluation Timing Decisions
| Stage | Benefit | Risk |
|---|---|---|
| Pre-commit (local) | Fast feedback, no CI queue | Developers may skip |
| Pull request CI | Mandatory gate, consistent | Pipeline latency |
| Plan-time (in Terraform) | Context-aware, sees actual values | Slows down apply |
| Admission (Kubernetes) | Blocks bad deployments at runtime | Latency impact |
One common setup is a pre-merge CI check, followed by a plan-time check against Terraform’s JSON plan. These are separate enforcement points: a source-file check can run without planned values, while a plan check can inspect values available at plan time. Neither check guarantees that later changes or runtime state remain compliant.
Production Failure Scenarios
Common Policy Failures
| Failure | Impact | Mitigation |
|---|---|---|
| Overly strict policies | Developers bypass policies or disable enforcement | Start permissive, tighten incrementally |
| Policy conflicts | Impossible to satisfy two policies simultaneously | Audit policy interactions before deployment |
| Slow policy evaluation | CI pipeline delays | Cache OPA decisions, optimize Rego queries |
| Policies not enforced in CI | Violations reach production | Make policy checks mandatory in pipeline |
| Rego bugs allow violations | False sense of compliance | Write comprehensive tests for every policy |
Policy Debug Flow
flowchart TD
A[Policy violation in CI] --> B[Run OPA locally]
B --> C[Verbose output: opa eval -v]
C --> D{Is violation real?}
D -->|Yes| E[Fix infrastructure code]
D -->|No| F[Fix policy Rego]
E --> G[Retry pipeline]
F --> G
Observability Hooks
Track policy evaluation and override events so the owner can investigate repeated failures and exceptions.
What to monitor:
- Policy violation rate per team or repository
- Most commonly violated policies
- Policy evaluation duration in CI
- Policy change frequency (too many changes may indicate instability)
- Exception request rate
# Evaluate the pinned OPA/Rego policy against Terraform plan JSON.
./opa eval --fail-defined --data policies/ --input plan.json 'data.terraform.analysis.deny[_]'
# Run the policy tests with the same OPA binary.
./opa test ./policies/ -v
Common Pitfalls / Anti-Patterns
Writing policies before understanding the data
OPA policies operate on input documents. For Terraform, that means plan.json or state.json—the JSON output from terraform show -json. Rego policies traverse this structure to find violations, so writing policies without knowing what that structure looks like is backwards.
Start by generating a plan and examining the raw JSON output. Run terraform init && terraform plan -out=plan.tfplan && terraform show -json plan.tfplan > plan.json, then open the file. Look at how resource types are named (aws_s3_bucket, not aws_s3), which attributes live under change.after versus change.before, and which fields are null versus missing entirely. These distinctions matter—a missing field and a null field behave differently in Rego.
What actually happens is the policy gets written against the Terraform provider documentation, which does not always match the JSON structure OPA sees. The docs might list server_side_encryption_configuration while the actual JSON key is sse_configuration. Booleans show up as strings "true" in some provider versions and proper booleans in others. Checking the actual data upfront resolves these mismatches before you write a single line of Rego.
For Kubernetes manifests, the input is the admission request object. Run OPA with --verbose or use opa eval with sample inputs to see the structure before writing policies. The same principle applies: inspect the actual document, not the expected document.
Making policies too broad
A policy that flags every resource creates noise and trains teams to ignore violations. Instead, target specific risky resources. “Deny S3 buckets without encryption” is actionable. “Deny resources without tags” is noisy when many resources legitimately lack tags.
The concrete cost is alert fatigue. When every resource in a pull request generates a violation, reviewers stop reading the output. A policy that returns 50 violations on a 10-resource change means the 2 real violations in that batch get missed. Teams learn to scroll past the policy check or disable it entirely, which defeats the purpose of enforcement.
The most common source of overly broad policies is copying a global rule from one context to another without adjusting the scope. A “deny untagged resources” rule that works fine in an AWS-only environment flags every Kubernetes pod, Cloud Foundry application, and SaaS resource when you extend policy enforcement across platforms. Before adding a global rule, ask whether it applies uniformly across every resource type in your infrastructure.
Narrowing a broad policy usually means choosing a resource type or a tag as the filter. Instead of “deny resources without cost-center tag,” write “deny aws_instance and aws_rds_instance resources without cost-center tag.” This is specific enough to catch the resources that actually generate cost attribution problems without flagging resources that cannot carry user-defined tags.
Audit existing policies for scope creep quarterly. Look for policies that generate more than 10% violation rate across your fleet—that is a signal the rule is either too broad or catching real problems that should be fixed at the source rather than blocked at the policy layer.
Not testing policies
Rego policies are code and can have bugs. A policy with a logic error might pass everything when it should deny, or deny everything when it should pass. OPA’s test framework categorizes failures into three types: false passes (a violating resource slips through undetected), false denies (a compliant resource gets flagged incorrectly), and unexpected exceptions (a test errors instead of producing the expected result). All three represent defects that ship to production if you skip testing.
OPA discovers rules prefixed with test_. The allow, deny, and exception tests above use Rego v1 and OPA v1.22.4. Run opa test ./policies/ -v; OPA returns a non-zero status if a test fails or errors. Tests record the cases the policy covers, but they do not prove that a control covers every risk or resource path.
Hardcoding exceptions in policies
When a legitimate use case violates a policy, the instinct is to add an exception directly in the Rego code. A not exception condition here, an allowed_account_ids list there. This works for the first few exceptions, but exception lists tend to grow indefinitely. Six months later, the policy that started as “deny S3 buckets without encryption” now has forty-seven exceptions for accounts that legitimately do not need encryption, and nobody can remember why each one exists.
The tested example above keeps the exception record in policies/exceptions.json and checks it by resource address and ticket ID. Keep an owner, reason, and expiry with each production exception, then review and remove it when the risk is resolved. The file is still policy input: changes to it need the same review and evidence as changes to Rego.
If a legitimate case cannot be handled by the policy itself and an exception feels necessary, treat that as a signal the policy needs rethinking. Either the policy is too broad and needs tighter scoping, or the legitimate case reveals a missing dimension in how the policy evaluates risk. When neither option works, escalate through a formal risk acceptance process. That documentation serves as audit evidence—the policy code itself is not the proof.
Interview Questions
Expected answer points:
- OPA operates on input documents—for Terraform, plan.json or state.json
- Terraform plan converts to JSON via `terraform show -json plan.tfplan`
- OPA Rego policies traverse the JSON document and return violations when conditions are met
- With the sample denial query, `opa eval --fail-defined` exits non-zero when the query finds a denial; an evaluation error also returns non-zero
Expected answer points:
- OPA: free, open-source, multi-cloud, uses Rego language
- Sentinel: commercial, HashiCorp-only, DSL with imperative-style policies
- AWS Policy: free, native AWS, IAM JSON/YAML for SCPs and Access Analyzer
- OPA is vendor-neutral; Sentinel locks to HashiCorp; AWS Policy locks to AWS
Expected answer points:
- Overly strict policies cause developers to bypass or disable enforcement
- Starting permissive identifies actual violations before fining-tune rules
- Too strict creates noise, trains teams to ignore violations, defeats purpose
- Incrementally tighten as policy library matures and exceptions get documented
Expected answer points:
- Run the pinned binary against the plan: `./opa eval --data policies/ --input plan.json 'data.terraform.analysis.deny'`
- Check if the violation is real—if yes, fix infrastructure code; if no, fix policy Rego
- Use `opa check` to verify Rego syntax without running
- Write comprehensive tests for every policy—Rego bugs cause false passes or false denies
Expected answer points:
- When a legitimate case violates a policy, instinct is to add exception
- Over time exceptions accumulate, policy becomes meaningless
- Instead: fix the policy to handle the legitimate case, or formalize risk acceptance
- Exception-based policies require ongoing maintenance to stay relevant
Expected answer points:
- conftest is a tool that applies OPA policies to configuration files
- Runs outside Terraform, validates HCL/Terraform code directly without plan
- Useful for pre-merge checks that do not require running actual plan
- `conftest test . --policy policy.rego` validates configs against policies
Expected answer points:
- Global policies catch everything but generate noise when teams have legitimate exceptions
- Resource-type policies target specific risky resources (S3 encryption, RDS public access)
- Global "deny untagged resources" is noisy; resource-type is actionable
- For most organizations, resource-type policies strike right balance between coverage and noise
Expected answer points:
- Separate data transformation from logic evaluation using helper functions
- Inline policies are shorter but harder to test in isolation
- Use packages to organize policies by domain (terraform.analysis, kubernetes.admission)
- Test each logical component independently, not just end-to-end
Expected answer points:
- Policy violation rate per team or repository—high rate indicates policy issues or training gap
- Most commonly violated policies—may need clearer documentation or easier to satisfy
- Policy evaluation duration in CI—slow evaluation indicates optimization opportunity
- Policy change frequency (too many changes = instability), exception request rate
Expected answer points:
- Pre-commit (local): fast feedback but developers may skip
- Pull request CI: mandatory gate, consistent, adds pipeline latency
- Plan-time (in Terraform): context-aware, sees actual values, slows down apply
- Standard approach is pre-merge CI with OPA/conftest; critical policies get second gate at plan-time
Expected answer points:
- `--fail-defined` makes `opa eval` return a non-zero status when the selected query produces a defined result
- It does not infer violations; the query must select the denial results, such as `data.terraform.analysis.deny[_]`
- OPA also returns a non-zero status for evaluation errors; a CI caller can use that status to block the job
- `--input plan.json` supplies the input document; `--data policies/` loads policy and exception data
- Without `--fail-defined`, the caller must inspect the result and decide whether to fail the job
Expected answer points:
- `deny` rules: when true, the policy result is a violation that blocks deployment
- `warn` rules: when true, the policy result is a warning that does not block deployment
- Use deny for hard requirements (encryption, no public access), warn for soft recommendations
- You can combine both: some policies deny, others warn depending on severity
- CI/CD pipelines can be configured to treat warnings as failures for stricter enforcement
Expected answer points:
- Use packages to organize policies by domain: `package terraform.analysis.deny`
- Create helper functions for common checks: `is_encrypted(rc)`, `has_required_tags(rc)`
- Package imports let you share functions across policy files
- Data documents allow external configuration without modifying policy code
- Test each helper function independently before composing into larger rules
Expected answer points:
- OPA evaluates plan JSON output, not HCL source—so computed values may not be available
- Some resource attributes only appear after apply, not in plan output
- OPA cannot validate things like exact IAM policy structure that requires evaluation
- Terraform state must exist for import and resource attribute lookups
- Large plans create large JSON that can slow down policy evaluation
Expected answer points:
- Sentinel is HashiCorp's policy-as-code language, available through products with a Sentinel integration
- Sentinel uses its own DSL with imperative-style policy writing
- OPA is open-source and vendor-neutral, and can evaluate plans locally or through an integration
- Sentinel policies can receive Terraform run data through the integrating product
- Porting policies between OPA and Sentinel is possible but requires rewriting Rego to Sentinel DSL
if and contains?Expected answer points:
- In OPA v1, `if` and `contains` are part of the standard Rego syntax
- `import rego.v1` makes Rego v1 syntax available on compatible pre-v1 OPA releases that support that import
- OPA v1.22.4 accepts the `import rego.v1` form used in these examples; language behavior depends on the OPA version
- Use the versioned Rego syntax documented in the language reference linked in the introduction
Expected answer points:
- Use external data documents to define exceptions rather than hardcoding in policy code
- Store the exception list as JSON/YAML and load it as Rego data, such as `data.exceptions` in the example
- Policy checks if the resource matches an exception before flagging violation
- Exception list reviewable and manageable without modifying policy logic
- Prevents policy code pollution from accumulated hardcoded exceptions
Expected answer points:
- Simple deny rules checking single attributes evaluate fast (milliseconds)
- Complex rules with nested iterations, multiple helper calls, and deep data traversal are slower
- For large Terraform plans, slow policies can add minutes to CI pipeline runtime
- Cache frequently evaluated policy decisions to avoid repeated computation
- Profile policy evaluation time with `opa eval --explain=full` to identify bottlenecks
Expected answer points:
- Write test cases using the `with input as` syntax to inject mock data
- Test positive cases: resources that should pass (no violation returned)
- Test negative cases: resources that should fail (violation returned)
- Run `opa test ./policies/ -v` for verbose test output with pass/fail per test
- Cover edge cases: null values, empty lists, unexpected data structures
Expected answer points:
- AWS Policy (IAM) governs what a specific identity can do—user, role, or service
- SCPs (Service Control Policies) govern what is denied at the organization level across all accounts
- Use IAM policies for fine-grained resource-level permissions per identity
- Use SCPs for guardrails that apply to all accounts: deny certain regions, require encryption
- SCPs are evaluated before IAM policies—SCPs can never grant permissions, only restrict them
Further Reading
- OPA Documentation - Official Open Policy Agent docs
- Rego Language Reference - Complete Rego syntax guide
- Conftest - OPA for configuration files
- Sentinel Documentation - HashiCorp Sentinel reference
- AWS Organizations Policies - AWS native policy enforcement
- OPA Gatekeeper - Kubernetes policy enforcement with OPA
Conclusion
Policy as code evaluates a defined set of rules against supplied input. OPA v1.22.4 with Rego v1 can run in different integrations, but each integration controls when and how it enforces a result. A passing evaluation covers only the checks and input included; it does not establish framework-wide compliance or guarantee that deployed systems remain compliant.
Start with a few high-impact policies—encryption requirements, tagging enforcement, publicly accessible resource restrictions. Expand coverage as your policy library grows and your team’s confidence with the tooling increases.
For more on DevOps practices, see our post on Cost Optimization which covers cloud cost governance patterns. For securing your infrastructure and IAM, see Cloud Security. For monitoring policy changes and compliance over time, see Observability Engineering.
Category
Related Posts
Compliance Automation: SOC 2, PCI-DSS, and Audit Trails
Automate compliance evidence collection and continuous compliance monitoring for SOC 2, PCI-DSS, and other frameworks using policy-as-code.
Choosing a Git Team Workflow
Compare trunk-based development, short-lived feature branches, and release branches against your release, review, rollback, and compliance needs.
Git Flow: The Original Branching Strategy Explained
Master the Git Flow branching model with master, develop, feature, release, and hotfix branches. Learn when to use it, common pitfalls, and production best practices.