Production-grade guide to compliance as code covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Compliance as code treats regulatory, contractual, and internal policy requirements as version-controlled software artifacts rather than static checklists or spreadsheet entries. Policies live in a repository, undergo review, are tested in pull requests, and are enforced automatically by tooling that evaluates them against running systems or built artifacts. This approach matters when compliance requirements change frequently, when organizations need to demonstrate audit readiness without manual labor, or when the cost of maintaining separate policy documentation diverges from the reality of system configuration. It is especially valuable in environments with many ephemeral resources—container clusters, serverless runtimes, or dynamically provisioned cloud infrastructure—where manual verification becomes infeasible and drift accumulates unnoticed.
The foundational step is expressing compliance rules in a declarative, evaluable language. The de facto standard in this space is Rego, the policy language of Open Policy Agent. A Rego policy is a set of rules that evaluate input data against defined obligations. Policies reside in files with the .rego extension and are loaded by the opa binary for evaluation.
The opa CLI is the primary interface for testing and running policies. A typical workflow begins with evaluating a single policy against sample data:
opa eval --input input.json policy.rego
The --input flag supplies a JSON document that serves as the data set against which the policy rules are evaluated. If the input contains fields that the policy references, OPA resolves those references during evaluation. Omit the flag to evaluate against an empty data document, which is useful for testing rule logic alone.
When a policy produces a result, OPA returns a JSON structure that includes the result array. Each element in the array corresponds to a rule that matched, with expressions detailing the rule name and value. A policy that finds a violation typically returns a result where the evaluated expression is true; a policy that finds no violations may return an empty result array or a result containing only false values, depending on how the policy is written.
Policies that reference data paths not present in the input document cause evaluation errors. OPA will halt with an error message like:
error: cannot find attribute "spec.image" in input data
This is not a syntax error—it is a runtime evaluation failure. Authors must ensure that the input data structure aligns with the paths referenced in Rego body statements. A frequent source of confusion is the distinction between input and data. The input document is ephemeral and supplied at evaluation time; data refers to the OPA document’s own body and imported packages, which are static unless the policy explicitly reads from input using data.document_name.something.
Another subtle issue arises from the --format flag. By default, opa eval outputs JSON. Requesting --format raw produces a plain‑text representation of the matched values, which can be easier to scan during development but omits the structured metadata (rule names, expression paths) that automated tooling expects. Switching formats mid‑workflow without adjusting downstream parsing logic is a common cause of integration failures.
A typical compliance check verifies that container images use non‑root users and avoid known‑vulnerable base layers. A Rego policy might look like this:
package image.compliance
deny[reason] {
not input.image.user == "root"
reason = ["image runs as root user"]
}
deny[reason] {
input.image.layers[_].vulnerability_count > 0
reason = ["image contains vulnerable layers"]
}
To evaluate this policy against a container manifest, the manifest must be serialized into a JSON document whose shape matches the input.image paths used in the policy. The opa eval command then becomes:
opa eval --input container_manifest.json policy.rego
If the manifest specifies user: "root", the first deny rule matches and appears in the evaluation output. If all layers have vulnerability_count: 0, the second rule does not fire.
Compliance as code achieves its strongest effect when policy evaluation is triggered automatically as part of the software delivery pipeline. The most common integration points are pull‑request checks and post‑build scans.
A GitHub Actions workflow can invoke OPA as a step in a job that runs on every pull request:
name: Policy Check
on:
pull_request:
branches: [ main ]
jobs:
compliance:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up OPA
run: |
curl -L -o /usr/local/bin/opa https://openpolicyagent.org/downloads/v0.65.0/opa_linux_amd64_static
chmod +x /usr/local/bin/opa
- name: Evaluate policies
run: |
opa eval --input ./policy-data.json policy.rego
The workflow fails if the opa eval command returns a non‑empty result array containing any true expressions. This gate prevents merged code that violates declared compliance rules. The policy-data.json file is typically committed alongside the policy and updated when legitimate infrastructure changes require a policy exception.
GitLab CI follows a similar pattern, using a job definition that references the opa binary:
compliance_check:
image: alpine:latest
stage: test
script:
- apk add --no-cache opa
- opa eval --input docker-image.json policy.rego
artifacts:
reports:
dotenv: compliance-report.env
The script section runs during pipeline execution. If the evaluation exits with a non‑zero status— which OPA does when the result array contains matching violations—the pipeline stops and the failure is reported in the merge request view.
Beyond CI/CD, compliance as code can govern what is allowed to enter a runtime environment. Kubernetes admission controllers are a primary venue for this, where OPA Gatekeeper extends the API server’s ability to validate or mutate resources before they are persisted.
Gatekeeper uses Rego policies called *constraints* to enforce rules across a cluster. A constraint is a custom resource that references a constraint template, which contains the Rego logic. The following is a conceptual representation of a constraint template structure:
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
name: templatecontainerimage
spec:
crd:
spec:
names:
kind: ConstraintTemplate
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package gatekeeper
deny[msg] {
input.review.object.spec.containers[_].image == "registry.example.com/badimage:latest"
msg = ["image is on deny list"]
}
Applied constraints are instances of the template:
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
name: deny-bad-image
spec:
match:
kinds:
apiGroups: [""]
kinds: ["Pod"]
template:
spec:
rego: |
package deny
deny[msg] {
input.review.object.spec.containers[_].image == "registry.example.com/badimage:latest"
msg = ["image is on deny list"]
}
When a Pod is created that references the denied image, the admission webhook rejects the request with an error message derived from the Rego msg variable. The rejected resource is not persisted, and the user receives a clear explanation of the policy violation.
A frequent operational issue is misalignment between the constraint’s match selection and the actual resources in the cluster. If a constraint targets kinds: ["Deployment"] but the policy is meant to apply to Pod resources, the constraint will have no effect on Pod creation events. The admission webhook passes through resources that do not match the constraint’s match criteria, silently allowing violations.
Another edge case involves policy rules that reference input.review.object.spec but the admission review payload uses a different sub‑path (e.g., input.review.request.object.spec for mutation versus input.review.object.spec for validation). Confusing these paths results in policies that never evaluate to a match, effectively becoming no‑ops. The OPA Gatekeeper documentation provides the exact payload shapes for each admission operation, but in practice, operators often copy Rego snippets from examples without adjusting the path prefix, leading to policies that appear enabled but never trigger.
Even with enforced compliance at intake, resources that were compliant at creation can become non‑compliant over time through manual changes, automated configuration management, or upgrade processes. Periodic scanning is required to identify drift.
conftest is a tool that wraps OPA evaluation against Kubernetes manifest files. It is commonly used in GitOps pipelines to validate that rendered manifests conform to policy before they are applied to a cluster.
A typical conftest configuration file (conftest.yaml) declares which policies to load and how to interpret results:
# conftest.yaml
policyPath: ./policy
policyFilters: [rego]
output:
format: table
Running a scan is a single command:
conftest test ./k8s-manifests/
The tool loads every .rego file found in the policyPath directory, evaluates it against each manifest in the target directory, and exits with a non‑zero status if any policy rule matches a violation. The default output format is a table showing the policy file, the rule that matched, and the manifest resource identifier. Custom formats can be selected with --format json for downstream tooling consumption.
A common pitfall is stale conftest caches. When a policy file is updated on disk, conftest may continue using a cached version unless the --force flag is supplied or the cache directory is cleared. In continuous integration environments, this can cause merged pull requests to pass policy checks even after a policy was tightened, because the cached evaluation result from a previous run is reused.
Container image compliance can be checked with OPA’s data command, which evaluates policies against image metadata extracted by the opea or anchore ecosystems. A representative command:
opa scan --data image-metadata.json policy.rego
The --data flag supplies a JSON document extracted from the image’s OCI layout or a prior scan tool’s output. The policy rules then inspect fields such as image.user, image.tags, or image.digest. If the policy finds a violation, opa scan exits with status 1 and prints the matching rule expressions. This pattern integrates readily into container registry webhooks or nightly cron jobs that scan newly pushed images.
The most common silent failure is a policy that references a data path absent from the evaluation input. OPA does not always surface this as a loud error; depending on the policy structure, it may simply produce no matches, leading the operator to believe the policy is inactive when it is actually waiting for data that will never arrive in the current context. Always validate policy‑input alignment with opa eval --input {} policy.rego to confirm that the policy either explicitly handles missing data or produces an error when the path is absent.
The --format flag on opa eval is frequently confused with the --format flag on conftest test. Both accept values like json, raw, and table, but they produce structurally different output. opa eval --format raw strips rule names and returns only matched values, while conftest --format raw may still include policy‑level metadata. Mixing these in a single script without explicit path to the desired output shape results in parsing errors downstream.
In long‑running CI pipelines, conftest’s internal cache can retain compiled Rego modules across job steps. If a policy file is updated mid‑pipeline (e.g., a policy hot‑fix merged to the main branch while a feature branch job is still executing), the running job may continue using the cached, older version of the policy. The practical remedy is to invoke conftest test with the --force flag in critical gates, or to structure pipelines so that policy updates trigger a fresh pipeline run rather than being injected into in‑flight jobs.
When Gatekeeper constraints are deployed, there is a brief window between constraint creation and the admission webhook picking up the new Rego logic. During this window, resources may be created that would be rejected once the webhook is fully warmed. Operators should treat the period immediately after constraint deployment as a “soft launch” and verify evaluation with opa eval against representative inputs before relying on the gate for hard blocks.
Policies, like application code, accumulate technical debt. A rule that was written for a specific infrastructure version may become obsolete as platforms evolve. There is no built‑in mechanism in OPA or conftest to automatically deprecate outdated rules; this responsibility falls to the policy‑maintenance workflow. Organizations typically tag policy files with version annotations or maintain a separate policy‑changelog.md that records when rules were added, modified, or retired. Without this discipline, the policy suite grows indefinitely, and the cost of running evaluations outweighs the benefit of the compliance signal they produce.
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.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy