Enforcing Kubernetes Security Policies with OPA Gatekeeper
How I built a reliable WhatsApp AI shopping assistant for Clickmothercare that survives hallucinated products, silent save failures, and multi-agent handoff bugs.
Kubernetes clusters are notoriously open by default, making policy enforcement a critical challenge for platform engineering teams. Without guardrails, a single misconfigured pod can expose the entire cluster to privilege escalation attacks or resource exhaustion. Open Policy Agent (OPA) Gatekeeper solves this by implementing Policy as Code via admission controllers.
The Problem: Unrestricted Privileged Containers
Allowing privileged containers enables processes inside the container to have almost the same privileges as those outside the container. This defeats the purpose of container isolation and is a primary vector for container breakout.
The Solution: OPA Gatekeeper ConstraintTemplate
We will define a ConstraintTemplate using the Rego policy language to strictly forbid privileged containers. Here is the implementation:
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sdisallowprivileged
spec:
crd:
spec:
names:
kind: K8sDisallowPrivileged
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sdisallowprivileged
violation[{"msg": msg}] {
c := input.review.object.spec.containers[_]
c.securityContext.privileged
msg := sprintf("Privileged container is not allowed: %v, securityContext: %v", [c.name, c.securityContext])
}
Rego Code Breakdown
Let's analyze the core Rego logic line-by-line to understand how it processes the admission request:
package k8sdisallowprivileged: Defines the namespace for our Rego policy, ensuring no collisions with other constraints.violation[{"msg": msg}] { ... }: The entry point for Gatekeeper. If the conditions inside the block evaluate to true, a violation is triggered and the admission request is denied.c := input.review.object.spec.containers[_]: This is where Rego shines. The_character acts as an iterator, looping through every container in the pod specification within the incoming Kubernetes API request (input.review.object).c.securityContext.privileged: This line asserts that theprivilegedflag within thesecurityContextof the current containercis set totrue. If it is omitted or false, the assertion fails, and the loop moves to the next container.msg := sprintf(...): Constructs a detailed error message identifying the offending container by name, which Gatekeeper returns to the user via the API server.
Applying the Constraint
Once the template is applied, you instantiate it to enforce the rule across specific namespaces. This decoupling of logic (Template) and application (Constraint) is what makes Gatekeeper scalable.
Is your AI agent's infrastructure secure and reliable?
Book a Free 15-Min Technical Audit