Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Gatekeeper, OPA for Kubernetes (CKS complement)

By updated

Improve this page

Logo Kubernetes

Gatekeeper is the Kubernetes project built around OPA (Open Policy Agent), a CNCF Graduated policy-as-code engine. It uses the Rego language (in French) to define complex policies through a ConstraintTemplate + Constraint model. It is a mature tool, widely adopted by teams that already know the OPA ecosystem.

The CKS curriculum covers Pod Security Standards, allowed registries, artifact validation and hardening; it does not name Gatekeeper as a required skill. This guide shows how to apply those controls with Gatekeeper if your team already uses it. For the native admission policies, see ValidatingAdmissionPolicy.

The outputs in this guide come from Gatekeeper v3.23.1 (Helm chart 3.23.1), on a kind cluster running Kubernetes 1.37, tested on 5 October 2026. Installing with Helm, with --wait, takes 36 seconds: the chart deploys a controller in three replicas and an audit controller, four Pods in total. The CKS exam itself is aligned with Kubernetes 1.35; nothing below depends on it.

What you will learn

  • Choose between Gatekeeper, VAP and Kyverno
  • Understand the ConstraintTemplate + Constraint model
  • Write security-oriented Rego policies (privileged, hostPath, runAsNonRoot)
  • Use gator to test locally
  • Diagnose an admission denial (Gatekeeper vs PSA vs RBAC)

When to choose Gatekeeper

Gatekeeper is not always the right choice. Learning Rego is a real investment, and you must know what it buys you. This table compares the three main approaches on concrete criteria.

CriterionVAPKyvernoGatekeeper
LanguageCEL (native K8s)YAMLRego
External componentNoYes (webhook)Yes (webhook)
Learning curveLowLowHigh
Complex logicLimitedMediumVery rich
Audit of existing resourcesNoPolicyReportsBuilt in
MutationGA in 1.36 (MutatingAdmissionPolicy)YesYes
Resource generationNoYesNo
Existing OPA ecosystemNoNoYes
CNCF maturityNative K8sGraduated (March 2026)Via OPA (Graduated)

In one sentence: choose VAP if you want to stay native, Kyverno for its YAML simplicity, or Gatekeeper if you already have an OPA/Rego ecosystem.

When to use Gatekeeper

These are the scenarios where Gatekeeper has a clear advantage:

  • You already use OPA elsewhere (Terraform, CI/CD, APIs)
  • Your team masters Rego
  • You need complex logic (cross-references, computations, sets)
  • You want a built-in audit of existing resources
  • You have a library of Rego policies to reuse

When NOT to use Gatekeeper

Conversely, these situations point to another tool:

  • You are new to policy-as-code → VAP or Kyverno
  • You want to avoid an external component → VAP
  • You need to generate resources → Kyverno
  • The team prefers to stay in plain YAML → Kyverno

Gatekeeper generates VAPs, but not from just any template

Gatekeeper can translate its constraints into native ValidatingAdmissionPolicy resources, and this is enabled by default. Two flags govern it, both marked beta and read directly from the binary:

Output of --help
-default-create-vap-for-templates
(beta) Create VAP resource for template containing VAP-style CEL source.
(default true)
-default-create-vap-binding-for-constraints
(beta) Create VAPBinding resource for constraint of the template
containing VAP-style CEL source. (default true)

The condition is in the wording, and it is decisive: "containing VAP-style CEL source". A ConstraintTemplate written in Rego produces no VAP: the constraint works and does block, but through the webhook. Only a template that declares a code block with engine: K8sNativeValidation triggers the generation.

The practical consequence matters for existing setups, because almost all public policy libraries are written in Rego. They will keep going through the webhook, and moving to the native path means rewriting them in CEL.

The thirty-second window

On a CEL template, the generation can be measured and happens in two steps:

Generated resourceDelay after the constraint is created
ValidatingAdmissionPolicy~2 seconds
ValidatingAdmissionPolicyBinding~30 seconds

This is not slowness, it is a setting: --default-wait-for-vapb-generation is 30 seconds by default. During that interval the VAP exists without its binding, and a VAP without a binding enforces nothing. So it is the Gatekeeper webhook that refuses during those thirty seconds, before the native path takes over.

The error message says it unambiguously, and it is the best way to know which path made the decision. Through the webhook:

Output
Error from server (Forbidden): admission webhook "validation.gatekeeper.sh"
denied the request: [require-team] the team label is required

Through the native policy, once the binding is in place:

Output
The pods "no-label" is invalid: : ValidatingAdmissionPolicy
'gatekeeper-k8slabelcel' with binding 'gatekeeper-k8slabelcel-require-team-cel'
denied request: a required label is missing

The boundary between "external tool" and "native mechanism" therefore does blur, but only for policies written in CEL: Gatekeeper coexists with VAP instead of replacing it. For a Rego template, the Constraint's status says so plainly: the vap.k8s.io enforcement point carries message: K8sNativeValidation engine is missing and state: error, while the webhook point is marked enforced. This is where to read which path a constraint really goes through.

Gatekeeper architecture

The diagram below shows what sets Gatekeeper apart from other admission tools: its two-level model. A ConstraintTemplate defines the logic in Rego and, along the way, creates a new resource type (a CRD) in the cluster. A Constraint is an instance of that type: it applies the template to a precise scope, with parameters. Look at the direction of the arrows: one template can be instantiated by several Constraints, so the rule is written once and applied per namespace or per team. Everything goes through the admission webhook, on the critical path of the API server.

Gatekeeper's two-level model: the ConstraintTemplate defines the logic, written in Rego, and is instantiated as a Constraint, which applies the policy with its parameters (labels, registries).instantiatesConstraintTemplatedefines the logicTemplate Regopolicy logicConstraintapplies the policyParameterslabels, registries
The Template defines the rule, the Constraint applies it. Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

Installation

Terminal window
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/v3.23.1/deploy/gatekeeper.yaml

In both cases the version is pinned: the manifest by its tag, the chart by --version. A helm install without a version takes the latest published one, and two clusters installed a week apart no longer run the same Gatekeeper. --wait returns once the four Pods answer, 36 seconds measured.

Check the installation:

Terminal window
kubectl get pods -n gatekeeper-system
Output
NAME READY STATUS RESTARTS AGE
gatekeeper-audit-74f586bd57-frrpr 1/1 Running 0 27s
gatekeeper-controller-manager-75d49687d6-bv4pt 1/1 Running 0 27s
gatekeeper-controller-manager-75d49687d6-k26qr 1/1 Running 0 27s
gatekeeper-controller-manager-75d49687d6-n7f8s 1/1 Running 0 27s

After installation you will see two kinds of pods. Understanding their role is essential for troubleshooting.

ComponentRoleReplicas
controller-managerAdmission webhook, intercepts and validates requests3 (HA)
auditPeriodic scan of existing resources1

Why 3 replicas for the controller-manager? It is a critical component on the API server path. If a single pod is down, admission requests could fail. With 3 replicas you get high availability.

The audit pod scans existing resources to detect violations. Even if a resource was created before Gatekeeper was installed, the audit will find it.

Example 1: deny privileged (high value for the CKS)

This example pays off the most for the CKS: refusing containers in privileged mode is a fundamental control.

apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sdenyprivileged
spec:
crd:
spec:
names:
kind: K8sDenyPrivileged
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sdenyprivileged
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
container.securityContext.privileged == true
msg := sprintf("Container '%v' in privileged mode is not allowed", [container.name])
}
violation[{"msg": msg}] {
container := input.review.object.spec.initContainers[_]
container.securityContext.privileged == true
msg := sprintf("InitContainer '%v' in privileged mode is not allowed", [container.name])
}

The ConstraintTemplate is created first. Gatekeeper then creates the K8sDenyPrivileged CRD it declares, a few moments later, and the CRD must then be established. Applying the Constraint too early returns no matches for kind "K8sDenyPrivileged".

Once the template is applied, the commands below wait in two steps. The until loop waits for the CRD to exist, because a kubectl wait run before that answers NotFound instead of waiting. Then kubectl wait waits for the CRD to be established. Then the Constraint is applied, and a privileged: true Pod is refused by the webhook; the message quotes the Constraint name in square brackets.

The loop is capped at 60 seconds. If it stops without the CRD existing, Gatekeeper could not create it, often because of an error in the template's Rego. Read the template status with kubectl get constrainttemplate k8sdenyprivileged -o yaml, field status.byPod[].errors.

debug-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: debug
spec:
containers:
- name: debug
image: nginx:1.30@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
securityContext:
privileged: true
Terminal window
timeout 60 sh -c 'until kubectl get crd k8sdenyprivileged.constraints.gatekeeper.sh >/dev/null 2>&1; do sleep 2; done'
kubectl wait --for=condition=established crd/k8sdenyprivileged.constraints.gatekeeper.sh
kubectl apply -f constraint.yaml
kubectl apply -f debug-pod.yaml
Output
Error from server (Forbidden): error when creating "debug-pod.yaml": admission webhook
"validation.gatekeeper.sh" denied the request: [deny-privileged-containers] Container 'debug'
in privileged mode is not allowed

Example 2: a complete securityContext (runAsNonRoot + readOnlyRootFilesystem)

For the CKS, enforcing a secure securityContext is even more relevant. The three Rego rules are independent, and that is what makes the message useful: a Pod with no securityContext at all gets all three violations at once, whereas a VAP in Deny mode returns only the first. Tested with a K8sSecurityContextComplete Constraint instantiated as in example 1:

Output
admission webhook "validation.gatekeeper.sh" denied the request:
[require-secure-context] Container 'nginx' must have allowPrivilegeEscalation: false
[require-secure-context] Container 'nginx' must have readOnlyRootFilesystem: true
[require-secure-context] Container 'nginx' must have runAsNonRoot: true
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8ssecuritycontextcomplete
spec:
crd:
spec:
names:
kind: K8sSecurityContextComplete
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8ssecuritycontextcomplete
# Check runAsNonRoot
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not container.securityContext.runAsNonRoot == true
msg := sprintf("Container '%v' must have runAsNonRoot: true", [container.name])
}
# Check allowPrivilegeEscalation
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not container.securityContext.allowPrivilegeEscalation == false
msg := sprintf("Container '%v' must have allowPrivilegeEscalation: false", [container.name])
}
# Check readOnlyRootFilesystem
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not container.securityContext.readOnlyRootFilesystem == true
msg := sprintf("Container '%v' must have readOnlyRootFilesystem: true", [container.name])
}

Example 3: deny hostPath (filesystem isolation)

A hostPath volume mounts a node directory straight into the container. It is a classic way out of isolation: mounting / or /var/run/docker.sock gives the pod access to the host system, often equivalent to a privilege escalation on the node. The template below refuses any pod that declares a hostPath volume, with no exception. The Rego rule is deliberately simple: it iterates over spec.volumes and rejects as soon as a volume carries the hostPath field, whatever the path value.

apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sdenyhostpath
spec:
crd:
spec:
names:
kind: K8sDenyHostPath
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sdenyhostpath
violation[{"msg": msg}] {
volume := input.review.object.spec.volumes[_]
volume.hostPath
msg := sprintf("hostPath volume '%v' is not allowed", [volume.name])
}

A Pod that mounts the host's /etc in a volume named host-etc is refused with [deny-hostpath] hostPath volume 'host-etc' is not allowed. Note what Rego does here without being asked: a Pod with no volume iterates over nothing, the rule produces no violation, and the Pod passes. In CEL, the same control needs an explicit has(object.spec.volumes), otherwise the missing field is an evaluation error.

Example 4: allowed registries (Supply Chain)

This example falls directly under the Supply Chain Security domain of the CKS, detailed in the Supply Chain Security guide.

apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sallowedregistries
spec:
crd:
spec:
names:
kind: K8sAllowedRegistries
validation:
openAPIV3Schema:
type: object
properties:
registries:
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sallowedregistries
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not registry_allowed(container.image)
msg := sprintf("Image '%v' comes from a registry that is not allowed", [container.image])
}
registry_allowed(image) {
registry := input.parameters.registries[_]
startswith(image, registry)
}

Matching Constraint:

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRegistries
metadata:
name: only-trusted-registries
spec:
enforcementAction: deny
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
registries:
- "gcr.io/my-project/"
- "registry.internal.company.com/"

startswith compares strings, without normalizing the image reference: nginx:1.30@sha256:…, which does come from Docker Hub, starts with none of the prefixes and is refused with [only-trusted-registries] Image 'nginx:1.30@sha256:…' comes from a registry that is not allowed. To allow Docker Hub, the list must carry docker.io/library/ and the manifests must spell the registry out in full, exactly as with a VAP.

Pod Security Standards with Gatekeeper

The official Gatekeeper library has a section dedicated to Pod Security Standards. For the CKS, this is Gatekeeper's strongest angle. The gatekeeper-library repository publishes no release and no tag: the only stable reference is a commit SHA, here the one of master on 5 October 2026, and it is the one used in the URLs. A raw.githubusercontent.com/.../master/... would change content without warning.

Terminal window
# Install the five Pod Security Standards templates (pinned commit)
LIB=https://raw.githubusercontent.com/open-policy-agent/gatekeeper-library/d2b86f87b0c98922d0765f6829bdabd75b3348e5/library/pod-security-policy
kubectl apply -f "$LIB/privileged-containers/template.yaml"
kubectl apply -f "$LIB/host-network-ports/template.yaml"
kubectl apply -f "$LIB/users/template.yaml"
kubectl apply -f "$LIB/capabilities/template.yaml"
kubectl apply -f "$LIB/host-filesystem/template.yaml"
PSS templateDescriptionPSA equivalent
K8sPSPPrivilegedContainerForbids privilegedBaseline/Restricted
K8sPSPHostNetworkingPortsControls hostNetwork/hostPortBaseline/Restricted
K8sPSPAllowedUsersRestricts UID/GIDRestricted
K8sPSPCapabilitiesControls capabilitiesRestricted
K8sPSPHostFilesystemRestricts hostPathBaseline

An installed template still refuses nothing: you must instantiate it with a Constraint, exactly as for a template you wrote yourself. This one applies K8sPSPPrivilegedContainer to all Pods outside the system namespaces:

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPPrivilegedContainer
metadata:
name: psp-privileged-container
spec:
enforcementAction: deny
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
excludedNamespaces:
- kube-system
- gatekeeper-system

The same debug-pod.yaml as above is then refused, this time with the library's message, which names the container and the offending field:

Output
Error from server (Forbidden): error when creating "debug-pod.yaml": admission webhook
"validation.gatekeeper.sh" denied the request: [psp-privileged-container] Privileged
container is not allowed: debug, securityContext.privileged: true

These templates perform the same controls as PSA, with more flexibility. You can, for example, allow hostPath in some namespaces only, which PSA cannot do: its level applies to the whole namespace.

Gatekeeper can thus complement PSA for specific rules it does not cover, or implement it entirely if you need more flexibility.

enforcementAction: progressive rollout

Deploying a policy straight in blocking mode is risky. Gatekeeper offers three enforcement modes for a gradual, safe adoption.

ValueBehaviorPhase
dryrunAccepts, records in statusDiscovery
warnAccepts, shows a warningAwareness
denyBlocks the requestProduction

How to use these modes?

  1. Start with dryrun: violations are recorded in the Constraint's status field, but no request is blocked. Run the audit to see the existing non-compliant resources.
  2. Move to warn: developers see warnings during their deployments but can carry on. This makes them aware before the blocking starts.
  3. Enable deny: once all workloads are compliant, switch to actual blocking.
spec:
enforcementAction: dryrun # Step 1: discovery
# enforcementAction: warn # Step 2: alert
# enforcementAction: deny # Step 3: enforcement

If you switch the example 1 Constraint to warn, the privileged Pod is created and kubectl shows the violation as a warning, with the same text as a denial. The switch is done with a kubectl patch on the Constraint; the template does not change.

Output (enforcementAction: warn)
Warning: [deny-privileged-containers] Container 'debug' in privileged mode is not allowed
pod/debug created

Audit: compliance of existing resources

A Constraint created today only applies to resources created or modified afterwards: admission fires on a request to the API server, and what is already running sends none. Without another mechanism you would have a cluster that is compliant on new deployments and blind to what already exists, which is precisely where accumulated drift sits.

The audit fills this gap. Gatekeeper periodically re-evaluates all the resources in the cluster against each Constraint, and writes the result in the Constraint's own status. Nothing is blocked or modified: the audit observes. That makes it the right starting point before switching a rule to deny, and also the field to read to measure a compliance debt.

Take a privileged Pod created in audit-demo before the Constraint: it is still running, and the first audit cycle, within the following minute, records it in the status. The interval is 60 seconds by default (--audit-interval), which is why a fresh violation can take up to a minute to appear.

Terminal window
# See the violations found by the audit
kubectl get k8sdenyprivileged deny-privileged-containers -o yaml
Excerpt of the status
status:
auditTimestamp: "2026-10-05T19:10:13Z"
totalViolations: 1
violations:
- enforcementAction: deny
group: ""
kind: Pod
message: Container 'debug' in privileged mode is not allowed
name: debug
namespace: audit-demo
version: v1

Test locally with gator

To try your templates and constraints locally, before any deployment, use gator rather than opa eval: it is the Gatekeeper CLI, and it natively understands its format. Testing as early as possible avoids exactly the scenario of the "In an emergency" section below: a faulty Constraint discovered in production.

Terminal window
# Install gator: release binary, checksum verified
curl -fsSLO https://github.com/open-policy-agent/gatekeeper/releases/download/v3.23.1/gator-v3.23.1-linux-amd64.tar.gz
curl -fsSLO https://github.com/open-policy-agent/gatekeeper/releases/download/v3.23.1/sha256sums.txt
grep gator-v3.23.1-linux-amd64.tar.gz sha256sums.txt | sha256sum -c -
tar xzf gator-v3.23.1-linux-amd64.tar.gz && sudo install gator /usr/local/bin/gator
# Evaluate a resource against a template and its constraint
gator test \
--filename template.yaml \
--filename constraint.yaml \
--filename debug-pod.yaml

On macOS, brew install gator installs the same binary. The gator test command exits with code 1 as soon as a violation is found and prints it, and with code 0 silently when the resource passes, which makes it an immediate pipeline gate:

Output (gator test, v3.23.1)
v1/Pod debug: ["deny-privileged-containers"] Message: "Container 'debug' in privileged mode is not allowed"

gator verify is not a Rego syntax check. It runs test suites: a Suite file declares, for each template and its Constraint, cases that say whether a given object must produce a violation or not. It is the equivalent of a unit test for a policy, and it is the one to plug into continuous integration.

suite.yaml
kind: Suite
apiVersion: test.gatekeeper.sh/v1alpha1
tests:
- name: deny-privileged
template: template.yaml
constraint: constraint.yaml
cases:
- name: pod-privileged-refused
object: debug-pod.yaml
assertions:
- violations: yes
- name: pod-plain-passes
object: pod-plain.yaml
assertions:
- violations: no
Output (gator verify suite.yaml)
ok suite.yaml 0.006s
PASS

Since v3.22+, gator policy even adds "brew-like" management of the policy library:

Terminal window
# Install policies from the library
gator policy install privileged-containers

Diagnosing an admission denial

A refused Pod can be refused by several mechanisms. Before assuming Gatekeeper is the cause, systematically check these possible sources. The error message usually tells you the source.

Message / HintLikely sourceDiagnostic command
admission webhook "validation.gatekeeper.sh" deniedGatekeeperkubectl get constraints
violates PodSecurityPSAkubectl get ns -o yaml (labels)
exceeded quotaResourceQuotakubectl describe quota
forbidden: User cannotRBACkubectl auth can-i
admission webhook "..." denied (other)Another webhookkubectl get validatingwebhookconfigurations

Gatekeeper diagnostic commands

These commands read from the general to the particular. Start by listing the active webhooks and Constraints to check what is really in place, then go down to the kubectl describe of one precise Constraint to see its violations in the status field. The last two commands target the logs: the controller-manager log traces admission denials in real time, the audit pod log reports violations on resources that are already deployed. Telling these two flows apart avoids looking for an admission denial in the audit logs, where it will not appear.

Terminal window
# List all webhooks
kubectl get validatingwebhookconfigurations
# List the ConstraintTemplates
kubectl get constrainttemplates
# List all active Constraints (action and audit violations as columns)
kubectl get constraints
# NAME ENFORCEMENT-ACTION TOTAL-VIOLATIONS
# k8spspprivilegedcontainer.../psp-privileged-container deny 1
# Details of a Constraint (violations, status)
kubectl describe k8sdenyprivileged deny-privileged-containers
# Controller logs (recent denials)
kubectl logs -l control-plane=controller-manager -n gatekeeper-system --tail=50
# Audit logs (violations on existing resources)
kubectl logs -l control-plane=audit-controller -n gatekeeper-system --tail=50

If kubectl get constraints answers the server doesn't have a resource type "constraints", this is not an admission denial: kubectl finds no Constraint type at all. Two causes are possible: no ConstraintTemplate has created a Constraint type yet, or the discovery cache of kubectl dates from before Gatekeeper was installed. The kubectl api-resources --categories=constraint command queries the server and refreshes that cache; if the list stays empty, apply a ConstraintTemplate first (example 1).

In an emergency

A Constraint that is too broad can block a deployment you must push through right now. The two escape hatches below do not have the same reach, and that is what should guide the choice under pressure.

Switching the Constraint to dryrun disarms only that one: the other rules keep protecting the cluster, and the audit keeps counting violations. This is the option to prefer. Deleting the webhook configuration disarms all policies at once, including those unrelated to the incident, and leaves the cluster with no admission control until it is recreated. Use it only if Gatekeeper itself is down.

Terminal window
# Option 1: switch the Constraint to dryrun
kubectl patch k8sdenyprivileged deny-privileged-containers \
--type='merge' -p '{"spec":{"enforcementAction":"dryrun"}}'
# Option 2: disable the webhook temporarily
kubectl delete validatingwebhookconfiguration gatekeeper-validating-webhook-configuration
# WARNING: remember to re-enable it after resolution

Mutation with Gatekeeper

Gatekeeper supports mutation (stable since v3.10+). This guide focuses on validation, but here is a minimal example:

apiVersion: mutations.gatekeeper.sh/v1
kind: Assign
metadata:
name: add-default-security-context
spec:
applyTo:
- groups: [""]
kinds: ["Pod"]
versions: ["v1"]
match:
scope: Namespaced
location: "spec.containers[name:*].securityContext.runAsNonRoot"
parameters:
assign:
value: true

For a complete guide to Gatekeeper mutation, see the official documentation.

Best practices

The recommendations below read in two stages. The first ones keep a policy from breaking the cluster it is meant to protect, a real risk as soon as Gatekeeper sits on the API server path. The second ones are about durability: a Rego Constraint that is not documented becomes unmanageable once its author changes team.

Security

These three rules answer a risk specific to Gatekeeper: since it sits on the API server path, a Constraint that is too broad can block the cluster itself, including the system pods that run it. The first rule is therefore the most important: exclude kube-system and gatekeeper-system from the scope of every Constraint. The second, starting in dryrun, lets you measure the impact before any blocking.

  1. Exclude the system namespaces (kube-system, gatekeeper-system) so you do not block the cluster
  2. Start in dryrun before deny, discover the violations with no impact
  3. Limit the scope with match.namespaces for performance

Operations

Day to day, the challenge is to keep policies maintainable over time. The first reflex saves the most time: start from the official library of policies rather than writing Rego from scratch, because the common cases (privileged, hostPath, capabilities) are already covered and tested there. The last point is not cosmetic: Rego is unreadable for anyone who does not practice it, so an undocumented Constraint becomes a blocking point as soon as its author leaves the team.

  1. Reuse the library before creating custom templates
  2. Test with gator locally before deploying
  3. Watch the audit for continuous compliance
  4. Document your Constraints, Rego is not readable by everyone

Performance

A broad constraint is expensive: every request to the API server triggers its evaluation, and a constraint that sweeps all the resources of the cluster is paid for in admission latency. Always limit the scope with match.namespaces and match.kinds, even when the rule could apply everywhere.

Put it into practice

In the lab, Gatekeeper is not installed. You install version v3.23.1 from the release manifest, then make it reject, in the entrepot namespace, any image that does not start with registry.k8s.io/. This takes a ConstraintTemplate that carries the logic in Rego, like the one in example 4, then a Constraint that applies it to entrepot only, with the allowed registry as a parameter. The match.namespaces field limits a Constraint to the listed namespaces. The entrepot-temoin namespace is the control: the rule must not apply there.

In entrepot, a Pod ancien-stock is already running with a Docker Hub image. Gatekeeper only checks new requests, so admission does not see it: the audit has to report it in the status of your Constraint. Do not delete it.

Validation checks three things. Gatekeeper's controller and audit run in gatekeeper-system, in v3.23.1. In entrepot, a Pod whose image comes from another registry is rejected at creation, while an image from registry.k8s.io/ is still accepted and entrepot-temoin still accepts a Docker Hub image. Finally, the audit of your Constraint lists ancien-stock.

Key takeaways

  1. Gatekeeper = OPA for Kubernetes, based on the CNCF Graduated OPA engine

  2. Two-level model: ConstraintTemplate (Rego logic) + Constraint (application)

  3. Rego: lets you write complex logic (cross-references, calculations), at the cost of a steep learning curve

  4. Built-in audit to scan existing resources, which VAP does not do

  5. gator to test locally (not opa eval)

  6. PSS library to implement the Pod Security Standards

  7. Admission webhook: a critical component, test outside production

  8. v3.22+ integrates VAP: Gatekeeper can coexist with native policies

Test your knowledge

These questions cover the ConstraintTemplate versus Constraint model, the choice between Gatekeeper, VAP and Kyverno, and the diagnosis of an admission denial.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
8 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer