#Why this matters
Even when SAST, SCA, and container scanners run cleanly in CI, security gaps still slip into production through configuration drift: a developer enables privileged: true on a debugging pod, mounts a host directory, or deploys directly with kubectl apply and bypasses the pipeline altogether. Security checklists stored on internal wikis cannot stop those changes at deploy time.
Policy as Code (PaC) turns architecture and compliance guardrails into executable, version-controlled rules. Using Open Policy Agent (OPA) and its declarative language Rego, teams write one set of security invariants, test them with unit tests, evaluate them in GitHub Actions before merge, and enforce them at the Kubernetes API server so non-compliant workloads are blocked consistently.
#Architecture of an end-to-end DevSecOps workflow
A mature DevSecOps workflow enforces security checks at multiple control points rather than relying on a single gate:
| Stage | Primary checks | Enforcement mechanism | Why it is needed |
|---|---|---|---|
| Pull request (CI) | SAST, SCA lockfiles, opa test, conftest test |
Required PR status check | Fast feedback before code merges |
| Build and release | Image build, SBOM, provenance attestation | Signed artifacts via OIDC | Prevents untrusted binaries from entering registry |
| Cluster admission | Kubernetes Pod Security, ingress, RBAC rules | OPA Gatekeeper validating webhook | Stops out-of-band kubectl or GitOps drift |
| Runtime and audit | Scheduled cluster policy sweeps | Gatekeeper dryrun / warn logs |
Catches existing drift as policies evolve |
Evaluating policies in CI gives developers sub-minute feedback inside their pull request, while enforcing the same rules in Kubernetes admission control guarantees that manual emergency commands or misconfigured controllers cannot bypass CI.
#Writing policies in OPA and Rego
OPA separates policy decision from policy enforcement. The caller (a CI runner or Kubernetes admission webhook) passes structured data as input to OPA, which evaluates .rego files and returns structured violations. Because Kubernetes manifests, Terraform plans, and GitHub Actions workflows all serialize cleanly to JSON, one policy engine covers the entire delivery chain.
Current OPA (with import rego.v1) uses explicit if and contains keywords to build sets of violation messages. Any rule inside deny contains msg if { ... } fires when all expressions inside the braces evaluate to true.
A classic Kubernetes bug occurs when policies only inspect input.spec.containers (which matches a standalone Pod) and miss input.spec.template.spec.containers (used by Deployment, StatefulSet, and DaemonSet), or forget initContainers. A helper rule normalises both shapes cleanly:
package kubernetes.pod_security
import rego.v1
pod_containers contains container if {
some container in input.spec.containers
}
pod_containers contains container if {
some container in input.spec.initContainers
}
pod_containers contains container if {
some container in input.spec.template.spec.containers
}
pod_containers contains container if {
some container in input.spec.template.spec.initContainers
}
deny contains msg if {
some container in pod_containers
container.securityContext.privileged == true
msg := sprintf("Privileged container not allowed: %s", [container.name])
}Because Rego is declarative, every deny rule should be paired with automated unit tests in a _test.rego file. Unit tests prevent accidental policy regressions that could either allow insecure pods or break every deployment in the cluster:
package kubernetes.pod_security
import rego.v1
test_deny_privileged_deployment if {
count(deny) > 0 with input as {
"kind": "Deployment",
"spec": {"template": {"spec": {"containers": [
{"name": "debug", "securityContext": {"privileged": true}},
]}}},
}
}
test_allow_unprivileged_pod if {
count(deny) == 0 with input as {
"kind": "Pod",
"spec": {"containers": [
{"name": "api", "securityContext": {"privileged": false, "allowPrivilegeEscalation": false}},
]},
}
}You can verify the policy locally with opa test and test real YAML manifests using Conftest:
$ opa test policy/ -v
policy/pod_security_test.rego:
data.kubernetes.pod_security.test_deny_privileged_deployment: PASS (412us)
data.kubernetes.pod_security.test_allow_unprivileged_pod: PASS (198us)
--------------------------------------------------------------------------------
PASS: 2/2
$ conftest test manifests/debug-pod.yaml -p policy/
FAIL - manifests/debug-pod.yaml - main - Privileged container not allowed: debug#Enforcing policies in GitHub Actions and Kubernetes
Once policies have unit tests, wire them directly into CI with minimal permissions so a pull request cannot change workflows or secrets during evaluation. In GitHub Actions, run opa test to validate the policy suite itself, then run conftest test against application manifests alongside SAST and SCA checks:
name: devsecops-policy-gate
on:
pull_request:
branches: [main]
permissions:
contents: read
jobs:
policy-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run Rego unit tests and manifest checks
run: |
opa test policy/ -v
conftest test manifests/ -p policy/Rolling out a strict policy across an existing cluster requires discipline. Turning OPA Gatekeeper directly to enforcementAction: deny on day one often breaks legitimate system DaemonSets or legacy services during a traffic spike. Follow a progressive rollout:
- Test in CI first: Block new pull requests with Conftest so new manifests comply immediately.
- Enable cluster audit (
dryrun): Deploy the GatekeeperConstraintwithenforcementAction: dryrun. Gatekeeper logs every violation in cluster status without dropping pods, revealing legacy exceptions safely. - Track exemptions as code: Grant narrow, namespace- or label-scoped exceptions with an expiration date and justification in Git, never cluster-wide disables.
- Switch to
deny: Oncedryrunviolation counts hit zero for compliant namespaces, flipenforcementActiontodeny.
#Common mistakes
- Checking
Podpaths only: Inspectinginput.spec.containerswithoutinput.spec.template.spec.containerslets insecureDeployment,DaemonSet, andCronJobworkloads pass silently. - Forgetting
initContainersandephemeralContainers: Attackers or misconfigured tooling can requestprivileged: truein an init container, gaining host access before the main container even starts. - Enforcing policy in CI without admission control: Pipeline checks alone do not stop someone with cluster credentials from running
kubectl editorkubectl applydirectly against the API server. - Skipping
_test.regounit tests: Untested Rego rules frequently contain typos in nested JSON keys that evaluate to undefined, causing thedenyrule to silently never fire.
#Summary
An end-to-end DevSecOps workflow pairs fast pull-request gates with non-bypassable runtime enforcement. Writing Policy as Code in OPA Rego lets teams validate Kubernetes manifests and IaC uniformly, prove rule correctness with opa test and conftest test in CI, and enforce the same invariants at cluster admission. Rolling out new constraints through dryrun audit mode and Git-tracked exemptions keeps production workloads stable while steadily raising the security baseline.