Kubernetes Admission Policies in 2026: Gatekeeper with Rego v1, and the Same Rules in ValidatingAdmissionPolicy
The problem
A Kubernetes cluster accepts almost anything that is valid YAML. Anyone who can create a pod can ask for a privileged container, which can take over the node. Anyone can pull an image from any registry on the internet. Namespaces appear with no owner, so when something breaks at 3 in the morning nobody knows whom to call.
In a cluster shared by many teams, written rules in a wiki do not stop any of this. The API server has to refuse the request, with a message that tells the person what to fix.
That is what admission policies do. Every create or update request passes through them before it is stored. This post builds three of them twice: once with OPA Gatekeeper, and once with ValidatingAdmissionPolicy, which is built into Kubernetes.
In 2023 I wrote OPA on Kubernetes: Security policies on Medium. Two things have changed since then.
- OPA 1.0 made Rego v1 the default syntax, so the old policies no longer parse without changes.
- Kubernetes 1.30 made ValidatingAdmissionPolicy generally available. Many rules that needed Gatekeeper can now run inside the API server itself.
This post walks through the same three rules both ways, on a local cluster, with the output you should see at each step. Everything is in github.com/snigdhasambitak/opa-policies, and its CI runs the policy unit tests on every change.
I tested every command below on Kubernetes 1.34 (kind), Gatekeeper 3.23 and OPA 1.23.
The three rules
- Every namespace must have a
teamlabel. - No container may run privileged.
- Pods in the
appsnamespace may only use images fromopenpolicyagent/.
What you need
git clone https://github.com/snigdhasambitak/opa-policies
cd opa-policies
kind create cluster --name policies
Part 1: Gatekeeper
Install it
helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts
helm install gatekeeper/gatekeeper --name-template=gatekeeper \
--namespace gatekeeper-system --create-namespace --wait
kubectl get deploy -n gatekeeper-system
NAME READY UP-TO-DATE AVAILABLE AGE
gatekeeper-audit 1/1 1 1 31s
gatekeeper-controller-manager 3/3 3 3 31s
The controller manager is the admission webhook the API server calls on every create and update. The audit pod checks objects that already exist, which matters later.
How a Gatekeeper policy is built
A policy comes in two parts.
- A ConstraintTemplate holds the Rego and defines a new resource kind, such as
K8sRequiredLabels. - A constraint is an instance of that kind. It says which objects to check and with which parameters.
So one template can back many constraints: “namespaces need team”, “pods need env”, and so on.
Rule 1: namespaces need a team label
The template is constraint-template-labels.yaml. This is the core of its Rego, in v1 syntax:
violation contains {"msg": msg, "details": {"missing_labels": missing}} if {
provided := {label | input.review.object.metadata.labels[label]}
required := {label | label := input.parameters.labels[_].key}
missing := required - provided
count(missing) > 0
def_msg := sprintf("you must provide labels: %v", [missing])
msg := get_message(input.parameters, def_msg)
}
View lines 55 to 62 of constraint-template-labels.yaml on GitHub
If you are coming from the 2023 version, the differences are contains and if. In Rego v1, violation[{"msg": msg}] { ... } is a parse error. The template also has to say which syntax it uses:
code:
- engine: Rego
source:
version: "v1"
rego: |
package k8srequiredlabels
...
View lines 39 to 44 of constraint-template-labels.yaml on GitHub
The constraint, constraint-instance-ns.yaml, applies it to namespaces:
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: all-ns-must-have-team-label
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Namespace"]
parameters:
message: "All namespaces must have a `team` label"
labels:
- key: team
View constraint-instance-ns.yaml on GitHub
Apply both, then try a labelled and an unlabelled namespace:
kubectl apply -f constraint-template-labels.yaml
kubectl apply -f constraint-instance-ns.yaml
kubectl apply -f example_allowed_ns.yaml
kubectl apply -f example_disallowed_ns.yaml
namespace/test-opa-2 created
Error from server (Forbidden): error when creating "example_disallowed_ns.yaml": admission webhook "validation.gatekeeper.sh" denied the request: [all-ns-must-have-team-label] All namespaces must have a `team` label
If applying the constraint fails with a no matches for kind error, Gatekeeper has not created the CRD from the template yet. Wait a few seconds and apply it again.
Rule 2: no privileged containers
constraint-template-priviledged.yaml checks containers, initContainers and ephemeralContainers. Checking only containers is the classic gap: a privileged init container gets through.
kubectl apply -f constraint-template-priviledged.yaml
kubectl apply -f constraint-instance-priviledge.yaml
kubectl apply -f example_allowed_pod.yaml
kubectl apply -f example_disallowed_pod.yaml
pod/nginx-privileged-allowed created
Error from server (Forbidden): error when creating "example_disallowed_pod.yaml": admission webhook "validation.gatekeeper.sh" denied the request: [psp-privileged-container] Privileged container is not allowed: nginx, securityContext: {"privileged": true}
Rule 3: only trusted image registries
constraint-allowed-repo.yaml only matches pods in the apps namespace. That namespace must carry a team label too, or rule 1 blocks it, so it comes from a file: apps-ns.yaml.
kubectl apply -f constraint-template-repos.yaml
kubectl apply -f constraint-allowed-repo.yaml
kubectl apply -f apps-ns.yaml
kubectl apply -n apps -f example_allowed_repo.yaml
kubectl apply -n apps -f example_disallowed_repo.yaml
namespace/apps created
pod/opa-allowed created
Error from server (Forbidden): error when creating "example_disallowed_repo.yaml": admission webhook "validation.gatekeeper.sh" denied the request: [repo-is-openpolicyagent] container <nginx> has an invalid image repo <nginx>, allowed repos are ["openpolicyagent/"]
Policies interact like this all the time. In a real cluster, roll out a new policy with enforcementAction: dryrun first and read the audit results before you switch it to deny.
Audit: what already breaks the rule
Admission only checks new and changed objects. The audit pod checks what is already there. After a minute or so:
kubectl get k8srequiredlabels all-ns-must-have-team-label
kubectl get k8srequiredlabels all-ns-must-have-team-label \
-o jsonpath='{range .status.violations[*]}{.name}{"\n"}{end}'
NAME ENFORCEMENT-ACTION TOTAL-VIOLATIONS
all-ns-must-have-team-label deny 6
local-path-storage
kube-system
kube-public
kube-node-lease
gatekeeper-system
default
Every namespace that existed before the policy is in breach. This report is the main thing Gatekeeper gives you that ValidatingAdmissionPolicy does not.
Part 2: the same rules with ValidatingAdmissionPolicy
ValidatingAdmissionPolicy runs inside the API server and uses CEL instead of Rego. There is nothing to install. Remove the Gatekeeper constraints first, so you know which one denies the request:
kubectl delete -f constraint-instance-ns.yaml \
-f constraint-instance-priviledge.yaml \
-f constraint-allowed-repo.yaml
kubectl delete ns test-opa-2
kubectl delete pod nginx-privileged-allowed
Rule 1 as a policy plus a binding, from vap/vap-required-labels-ns.yaml:
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: all-ns-must-have-team-label
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["namespaces"]
validations:
- expression: "has(object.metadata.labels) && 'team' in object.metadata.labels"
message: "All namespaces must have a `team` label"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: all-ns-must-have-team-label
spec:
policyName: all-ns-must-have-team-label
validationActions: [Deny]
View vap/vap-required-labels-ns.yaml on GitHub
The policy says what to check. The binding says where it applies and what to do on failure. validationActions: [Warn, Audit] is the equivalent of Gatekeeper’s dry run.
The privileged rule in vap/vap-privileged.yaml uses variables to build the list of all containers once, then checks it:
variables:
- name: containers
expression: >-
(has(object.spec.containers) ? object.spec.containers : []) +
(has(object.spec.initContainers) ? object.spec.initContainers : []) +
(has(object.spec.ephemeralContainers) ? object.spec.ephemeralContainers : [])
- name: privileged
expression: >-
variables.containers.filter(c, has(c.securityContext) &&
has(c.securityContext.privileged) && c.securityContext.privileged).map(c, c.name)
validations:
- expression: "size(variables.privileged) == 0"
messageExpression: "'Privileged container is not allowed: ' + variables.privileged.join(', ')"
View lines 13 to 25 of vap/vap-privileged.yaml on GitHub
Apply the three policies and run the same examples:
kubectl apply -f vap/vap-required-labels-ns.yaml
kubectl apply -f vap/vap-privileged.yaml
kubectl apply -f vap/vap-allowed-repo.yaml
kubectl apply -f example_allowed_ns.yaml
kubectl apply -f example_disallowed_ns.yaml
kubectl apply -f example_allowed_pod.yaml
kubectl apply -f example_disallowed_pod.yaml
kubectl apply -n apps -f example_disallowed_repo.yaml
namespace/test-opa-2 created
The namespaces "test-opa-3" is invalid: : ValidatingAdmissionPolicy 'all-ns-must-have-team-label' with binding 'all-ns-must-have-team-label' denied request: All namespaces must have a `team` label
pod/nginx-privileged-allowed created
The pods "nginx-privileged-disallowed" is invalid: : ValidatingAdmissionPolicy 'psp-privileged-container' with binding 'psp-privileged-container' denied request: Privileged container is not allowed: nginx
The pods "nginx-disallowed" is invalid: : ValidatingAdmissionPolicy 'repo-is-openpolicyagent' with binding 'repo-is-openpolicyagent' denied request: Invalid image repo, allowed repos are [openpolicyagent/]: nginx <nginx>
Same decisions, no webhook. If a request is still denied by a policy you just deleted, wait a few seconds. The API server takes a moment to drop it.
Test the policies before they reach a cluster
A policy is code, so it gets unit tests. Each Rego file has a test in tests/. Here is part of tests/k8srequiredlabels_test.rego:
test_namespace_without_team_label_denied if {
count(k8srequiredlabels.violation) == 1 with input as {
"review": {"object": {"metadata": {"name": "apps"}}},
"parameters": params,
}
}
View lines 14 to 19 of tests/k8srequiredlabels_test.rego on GitHub
The Rego lives inside YAML templates, so the Makefile copies it out with yq first, then formats, checks and tests it:
make fmt check test
data.k8srequiredlabels_test.test_namespace_without_team_label_denied: PASS
data.k8spspprivileged_test.test_privileged_init_container_denied: PASS
data.k8sallowedrepos_test.test_disallowed_repo_denied: PASS
...
PASS: 24/24
The same targets, plus a schema check of every manifest with kubeconform, run in GitHub Actions on every pull request.
The repo also uses OPA outside Kubernetes, to check Terraform plans for allowed instance profiles and required tags. The README has the commands.
What can go wrong
Your own policy blocks your setup. Once namespaces need a team label, kubectl create namespace apps is denied too. Create namespaces from a file that carries the label, as apps-ns.yaml does.
The constraint is applied before its kind exists. Gatekeeper creates the constraint CRD a few seconds after you apply the template. Applying the constraint in the same breath fails with no matches for kind. Apply it again.
Old Rego no longer parses. violation[{"msg": msg}] { ... } is Rego v0. OPA 1.0 and later need contains and if, and the template needs version: "v1".
Checking only containers. A privileged init container or ephemeral container gets through. Check all three lists, as both versions of rule 2 do.
A deleted ValidatingAdmissionPolicy still denies for a few seconds. The API server refreshes its policy cache in the background. Wait before you retest.
Gatekeeper is down and nobody notices. The Helm chart installs the validating webhook with validatingWebhookFailurePolicy: Ignore and a 3 second timeout. If Gatekeeper cannot answer, the API server lets the request through unchecked. Setting it to Fail closes that gap, but then an unhealthy Gatekeeper blocks every matching request, so run several replicas with a PodDisruptionBudget and alert on webhook errors. ValidatingAdmissionPolicy has no pod that can be down.
Turning a policy on in deny mode on day one. Existing workloads may break on their next update. Start with enforcementAction: dryrun in Gatekeeper, or validationActions: [Warn, Audit] in a binding, and read the results first.
Which one should you use?
| Gatekeeper | ValidatingAdmissionPolicy | |
|---|---|---|
| Runs in | A webhook in the cluster | The API server |
| Language | Rego | CEL |
| Extra components | Controller and audit pods | None |
| Report on existing objects | Built in | Not included |
| Mutation | Supported | No, validation only |
| Rules that need other cluster data | Possible, with data replication | Limited to the object, its namespace and parameters |
For simple rules like these three, I would start with ValidatingAdmissionPolicy. It has no extra pods to run and no webhook that can fail open or block deploys. Gatekeeper is worth it when you need the audit report, mutation, or Rego that looks at other objects. Gatekeeper can also run CEL in its templates and generate ValidatingAdmissionPolicies for you, so choosing it does not lock you out of the native path.
When you are done:
kind delete cluster --name policies