Policy As Code Enforcement

Production-grade guide to policy as code enforcement covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Policy as code enforcement moves security, compliance, and operational guardrails from manual checklists into automated, versioned, and testable rules. It matters whenever you need consistent enforcement across many environments, when audit trails are required for regulators, or when manual review becomes a bottleneck in CI/CD pipelines or infrastructure provisioning. This page covers the concrete steps of writing, testing, and enforcing policies as code, using tooling that exists and works across platforms.

Writing a Rego Policy

Policies are expressed in Rego, a declarative language that evaluates input documents against rules you define. The most common entry point for exploring a policy without a running server is the opa CLI.

Create a file named policy/rego/review.rego:

package k8s.admission

deny[reason] {
    input.review.object.spec.containers[_].runAsNonRoot == false
    reason = "Containers must run with runAsNonRoot enabled"
}

This rule fires when a container definition lacks runAsNonRoot: true. The deny keyword returns a binding; the reason variable is included in the output so enforcement tooling can surface a message to the operator.

To evaluate the rule against a sample admission review, use opa eval with the --input flag:

opa eval --input '{"review":{"object":{"spec":{"containers":[{"name":"app","runAsNonRoot":false}]}}}}' 'data.k8s.admission.deny'

Because the container runs without runAsNonRoot, the command returns a non‑empty result:

[
  {
    "reason": "Containers must run with runAsNonRoot enabled"
  }
]

If the same command is run with runAsNonRoot: true, opa eval returns an empty JSON array [], indicating the rule does not match.

Unit‑testing policies is done with opa test. Place test cases alongside the policy or in a dedicated policy/test/ directory. A minimal test file policy/test/root.rego:

package k8s.admission.tests

test_no_root_violation {
    deny with input {"review":{"object":{"spec":{"containers":[{"name":"app"}]}}}}
}

Run the test suite from the project root:

opa test ./policy/

Output:

ok: 1 passed

If the policy is intentionally inverted (e.g., the condition reads runAsNonRoot == true), the same opa test command produces:

FAIL: test_no_root_violation (1 utest)

opa test exits with a non‑zero status when any test fails, making it suitable for CI gates.

Running Policy Tests in a CI Pipeline

Integrating policy checks into a continuous integration workflow typically involves invoking opa test from a shell step and treating a non‑zero exit code as a build failure. The following snippet illustrates a GitHub Actions job that enforces the policy package on every push:

jobs:
  enforce-policy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Install OPA
        run: |
          curl -L -o /usr/local/bin/opa https://openpolicyagent.org/downloads/v0.68.0/opa_linux_amd64_static
          chmod +x /usr/local/bin/opa
      
      - name: Run policy tests
        run: |
          set -o pipefail
          opa test ./policy/

If any test in ./policy/ fails, the step exits with failure and the workflow stops. This pattern works with any CI system that can execute a bash script; the only requirement is that the opa binary is available on the runner.

Enforcing Policies Against Kubernetes Admission Reviews

In a Kubernetes cluster, policies often gate mutating or validating admission requests. The mechanics are the same: the admission webhook forwards the review JSON to OPA, OPA evaluates the Rego rules, and returns an allow/deny decision with optional messages.

A typical review JSON saved as review.json might look like:

{
  "requestKind": "Pod",
  "requestVersion": "v1",
  "object": {
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": {"name": "my-pod"},
    "spec": {
      "containers": [
        {"name": "app", "image": "nginx"}
      ]
    }
  }
}

Evaluating the policy against this file:

opa eval --input review.json 'data.k8s.admission.deny'

Because the example Pod does not set runAsNonRoot, the output again is:

[
  {
    "reason": "Containers must run with runAsNonRoot enabled"
  }
]

The admission webhook would interpret this non‑empty output as a denial and return HTTP 403 with the reason text to the caller. If the policy were adjusted to permit the resource (e.g., by adding a condition that checks for an allowed label), the same opa eval would return [], and the request would proceed.

In production, many teams run an OPA server as a sidecar or gateway and send every admission review to http://localhost:8181/v1/data/k8s/admission/deny via POST. The server’s response shape is always {"result":{"expressions":[{"value":true/false,"text":"..."]}}}, but the underlying evaluation logic—the Rego rules, the input schema, the exit behavior—is identical to the CLI workflow described above.

Debugging a Policy Violation

When a CI job or admission request unexpectedly passes a policy that should deny, the first diagnostic step is to capture the raw opa eval output and inspect it outside the CI context.

A common pattern:

RESULT=$(opa eval --input ./review.json 'data.k8s.admission.deny' 2>&1)
echo "opa eval output: $RESULT"
if echo "$RESULT" | grep -q '"reason"'; then
  echo "Policy was enforced. Reason: $(echo "$RESULT" | jq -r '.[0].reason')"
  exit 1
else
  echo "Policy did not match. Input may be missing expected fields."
  exit 0
fi

Typical failure modes include:

Known Gotchas and Silent Failures

Policy reload and caching OPA compiles Rego into highly optimized internal representations. When a policy file on disk is edited, opa eval picks up the change on the next invocation because it reads the file fresh each time. However, OPA servers that load policies at startup cache the compiled form. A policy change on a running server requires either a SIGHUP signal (if the server supports hot reload) or a restart. Omitting this step is a frequent source of “policy appears unchanged” incidents in production.

Empty or missing input fields Rego rules that reference array indices or object keys absent from the input do not throw an error by default; they simply produce no match. If a rule is written as input.review.object.spec.containers[_].runAsNonRoot == false, and the input Pod has zero containers, the rule yields []. Enforcement logic that checks if [ -n "$(opa eval …)" ] will treat this as “no violation,” which is often the opposite of the intended behavior. Explicitly validating that required input paths exist before evaluation can prevent this class of silent allow.

Performance at scale Large policy packages (hundreds of rules, deep nesting) can increase evaluation latency into the seconds range. On CI runners with tight time budgets, this may cause flaky timeouts. A common mitigation is to split concerns into focused policy packages (e.g., one package for container security, another for resource quotas) and invoke only the relevant subset per pipeline stage. The opa build command can pre‑compile packages into a single binary artifact, reducing per‑invocation overhead.

Flag confusion The --format flag accepts json, raw, and text. --format raw outputs the bare binding values without the wrapping JSON array, which can be easier to pipe into grep or jq. --format text prints each binding on a separate line, which is convenient for human readability but may break JSON‑parsing downstream. Using --format json is the safest choice for programmatic consumption, but teams sometimes default to raw and later encounter unexpected output shapes when the rule returns multiple bindings. Verifying the format in a local opa eval dry‑run before embedding it in a script prevents downstream surprises.

This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.