You have a cluster with workloads from multiple teams and you need to enforce baseline rules — every pod has resource limits, no privileged containers, images come from approved registries, namespaces carry owner labels. You can do it with PodSecurityAdmission for the security bits, but the rest needs OPA Gatekeeper. This article is the operating procedure we follow: install, author one ConstraintTemplate, dry-run audit until clean, enforce, then expand.
How to verify
The Gatekeeper controllers should be running:
kubectl -n gatekeeper-system get pods
ConstraintTemplates and Constraints should be listable:
kubectl get constrainttemplates
kubectl get constraints -A
A specific Constraint’s audit results show non-compliant resources:
kubectl get k8srequiredlabels -A
kubectl describe k8srequiredlabels namespace-must-have-owner
A test deployment that violates a constraint should be rejected:
kubectl create ns test-bad --dry-run=server -o yaml | kubectl apply -f -
What’s happening
Gatekeeper is an admission webhook that runs OPA (Open Policy Agent) Rego policies against every API request. The split is intentional: ConstraintTemplate defines the policy logic (Rego code), Constraint is an instance of that template scoped to specific kinds and parameters. One template + many constraints is the supported pattern.
The controller runs in two modes for any given Constraint: deny (default — admission webhook rejects violating requests) and dryrun (admission lets violations through but the audit job records them). The audit job runs every minute by default, walks the cluster for cached objects that violate constraints, and writes violations into the Constraint’s .status. This is what lets you roll out without breaking everything — start in dryrun, watch audit results, fix what’s broken, then switch to deny.
The procedure
-
Install Gatekeeper via the Helm chart.
helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts helm install gatekeeper gatekeeper/gatekeeper \ --namespace gatekeeper-system \ --create-namespace \ --version 3.18.0 \ --set replicas=3 \ --set audit.replicas=1 \ --set auditInterval=60 \ --set constraintViolationsLimit=100 -
Write a ConstraintTemplate for a real rule. Example: every namespace must carry an
ownerlabel.apiVersion: templates.gatekeeper.sh/v1 kind: ConstraintTemplate metadata: name: k8srequiredlabels spec: crd: spec: names: { kind: K8sRequiredLabels } validation: openAPIV3Schema: type: object properties: labels: type: array items: { type: string } targets: - target: admission.k8s.gatekeeper.sh rego: | package k8srequiredlabels violation[{"msg": msg}] { required := input.parameters.labels provided := {label | input.review.object.metadata.labels[label]} missing := required[_] not provided[missing] msg := sprintf("missing required label: %v", [missing]) }Apply it:
kubectl apply -f constrainttemplate-required-labels.yamlThis creates a new CRD
K8sRequiredLabelsin the cluster. -
Create a Constraint that uses the template in dryrun.
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredLabels metadata: name: namespace-must-have-owner spec: enforcementAction: dryrun match: kinds: - apiGroups: [""] kinds: ["Namespace"] parameters: labels: ["owner"] -
Watch the audit results. After a minute or two, audit should populate
.status.violations:kubectl get k8srequiredlabels namespace-must-have-owner -o jsonpath='{.status.violations}' | jqEach violation lists the resource and the message. Fix each one by adding the label.
-
Promote to deny once audit is clean. Edit the Constraint:
kubectl patch k8srequiredlabels namespace-must-have-owner \ --type merge \ -p '{"spec":{"enforcementAction":"deny"}}'New namespaces missing the label are now rejected. Existing namespaces stay (admission doesn’t fire on existing objects), but they continue to show up in audit until you label them.
-
Build a constraint library. Common templates worth shipping early: image registry allowlist, required resource limits/requests, disallow privileged, disallow hostPath volumes, required PodDisruptionBudget for Deployments with replicas > 1, namespace-scoped quotas. Many are pre-written in the gatekeeper-library repo.
Operational notes
- Audit cache TTL controls staleness. Default is one hour for unused cache entries. A cluster with many namespaces and a 1-minute audit interval can be noisy; tune
auditChunkSizeto limit how many resources are examined per cycle. - Mutating webhooks change object shape before constraints see it. A constraint that checks for
resources.limitsmust run after the LimitRange mutator. UsefailurePolicy: Failwith care — order matters for chained webhooks. dryrunandwarnare different.dryrunlets the admission pass and only writes audit;warnreturns a warning to the user but still admits.warnis useful during migration;dryrunis invisible.- ConstraintTemplate updates require version bumps. Editing Rego in place reloads the policy at the next reconcile; if a syntax error sneaks in, audit stops. Always test templates in a dev cluster first.
- External data and image signing checks are separate features. Gatekeeper supports external-data providers (HTTP callouts for things like registry lookups) and integrates with cosign for image signing via the Mutate-and-Validate pattern. Treat them as add-ons — they have their own scaling and reliability story.
Stack Harbor designs and operates the Gatekeeper policy catalogue for clusters under our care — base templates from the upstream library, custom templates for client-specific rules, the dryrun-then-deny rollout, and the audit dashboard that surfaces drift before it reaches production. See how we deliver that within managed Kubernetes operations, and compare with kyverno-policies-validation for the YAML-native alternative.