Enforcing Kubernetes Policies with Kubectl and Open Policy Agent
The cluster was running, but something was wrong. A kubectl command slipped through that should have been blocked. That’s when you realize: Kubernetes alone doesn’t decide what’s allowed. You need Open Policy Agent.
Kubectl and OPA work together to enforce fine-grained, declarative policies in your cluster. kubectl applies changes. OPA evaluates requests against rules you control. With this pairing, you can stop dangerous deployments before they reach the API server.
Install OPA as an admission controller. Write policies in Rego, OPA’s query language. Define what counts as compliant: require image signatures, block privileged pods, enforce namespace restrictions. Apply policies to every kubectl request—create, update, delete.
When kubectl sends a request, the API server calls OPA’s webhook. OPA runs your Rego policy. If the request violates a rule, OPA denies it. This is real-time, policy-as-code control.
Key benefits of using kubectl with OPA:
- Centralized enforcement: every cluster request passes the same checks.
- Declarative rules: store policies in Git, review with code.
- Audit visibility: log every decision and reason.
- Instant rollback of risky policy changes.
Start with a simple Rego policy:
package kubernetes.admission
deny[msg] {
input.request.kind.kind == "Pod"
input.request.object.spec.containers[_].securityContext.privileged == true
msg := "Privileged containers are not allowed"
}
Deploy OPA, point the Kubernetes API server --admission-control-config-file to it, and watch kubectl obey your rules.
Best practices:
- Keep policies small and composable.
- Test with
opa evalbefore pushing to production. - Version-control everything.
- Integrate with CI to prevent bad configs from ever reaching
kubectl.
Kubernetes security depends on policy. With kubectl and Open Policy Agent working together, you gain the power to enforce rules at the gate, not after the breach.
Try it in minutes with hoop.dev and see live policy enforcement without touching your local kubeconfig.