Opscraft
Open Policy Agent · Lesson 3 of 9 · 7 min read

Gatekeeper: OPA for Kubernetes admission

Architecture

Gatekeeper runs in the cluster (namespace gatekeeper-system) and registers itself with the API server as a validating admission webhook (and optionally a mutating one). For every matching create/update request, the API server sends an AdmissionReview to Gatekeeper, which evaluates the relevant policies and returns allowed/denied with messages.

Enlarge diagramkubectl applyauthn + authzmutatingwebhooksGatekeepervalidatingwebhookallow / denywith a message
Figure 1. Where Gatekeeper sits: after authentication, authorization and mutation, as a validating webhook that allows or denies with a message.
Swipe sideways to see all of it, or tap to open it full screen.

Components:

  • Webhook pods (run several replicas) — answer admission requests.
  • Audit controller — periodically (default about every 60 seconds) evaluates existing resources against constraints and writes violations into each Constraint's status — catches things created before the policy existed or that bypassed admission.
  • Controller manager — compiles ConstraintTemplates into CRDs.

ConstraintTemplate and Constraint

Enlarge diagramConstraintTemplatek8srequiredlabels: Rego logic + parameterschema → creates kind K8sRequiredLabelsConstraintkind K8sRequiredLabels · match:Namespaces · labels: [owner] · action: denyinstance of
Figure 2. Gatekeeper's two halves: a template holds reusable logic and creates a new kind; a constraint uses that kind with parameters and a scope.
Swipe sideways to see all of it, or tap to open it full screen.

Gatekeeper splits a policy into two parts:

  • ConstraintTemplate — the reusable Rego logic plus a parameter schema. Creating one defines a new CRD kind.
  • Constraint — an instance of that kind: which resources it applies to (match), its parameters, and its enforcement action.
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, "details": {"missing_labels": missing}}] {
        provided := {label | input.review.object.metadata.labels[label]}
        required := {label | label := input.parameters.labels[_]}
        missing := required - provided
        count(missing) > 0
        msg := sprintf("you must provide labels: %v", [missing])
      }
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: namespaces-must-have-owner
spec:
  enforcementAction: dryrun           # deny | dryrun | warn
  match:
    kinds:
    - apiGroups: [""]
      kinds: ["Namespace"]
    excludedNamespaces: ["kube-system", "gatekeeper-system"]
  parameters:
    labels: ["owner", "cost-centre"]

Notes:

  • In Gatekeeper templates, the object is at input.review.object (and input.review.oldObject for updates), parameters at input.parameters.
  • Rules must be named violation and produce objects with a msg (optional details).
  • The template above uses the classic Rego syntax common in the Gatekeeper library.
  • match supports kinds, namespaces, excludedNamespaces, labelSelector, namespaceSelector, scope (Namespaced/Cluster).

Enforcement actions

Action Effect
deny Request rejected with the message
warn Request allowed; kubectl shows a warning
dryrun Request allowed; violations only recorded by audit
Enlarge diagramdryrunallowed; only audit records itwarnallowed; kubectl prints awarningdenyrejected with the message
Figure 3. Enforcement actions, from gentle to strict. New rules start at dryrun or warn.
Swipe sideways to see all of it, or tap to open it full screen.

The Gatekeeper policy library

The community library has ready-made templates — use them instead of writing your own where possible:

  • K8sAllowedRepos — images only from approved registries (e.g. your ECR prefix).
  • K8sContainerLimits / K8sRequiredResources — CPU/memory limits and requests required.
  • K8sPSPPrivilegedContainer, K8sPSPHostNamespace, K8sPSPCapabilities, K8sPSPReadOnlyRootFilesystem... — Pod Security equivalents.
  • K8sRequiredLabels, K8sRequiredProbes, K8sBlockNodePort, K8sDisallowedTags (latest), K8sUniqueIngressHost, K8sBlockLoadBalancer.

Referential policies: syncing cluster data

Some policies need other objects — "Ingress hosts must be unique across the cluster" needs all existing Ingresses. Configure Gatekeeper's sync (the Config resource, or SyncSet in newer versions) to replicate selected kinds into OPA's cache, available under data.inventory:

apiVersion: config.gatekeeper.sh/v1alpha1
kind: Config
metadata: { name: config, namespace: gatekeeper-system }
spec:
  sync:
    syncOnly:
    - { group: "networking.k8s.io", version: "v1", kind: "Ingress" }
    - { group: "", version: "v1", kind: "Namespace" }
  match:
  - excludedNamespaces: ["kube-system"]
    processes: ["*"]

Gatekeeper also supports external data providers for lookups outside the cluster (e.g. verifying image signatures).

Enlarge diagramexisting Ingressesin the clusterGatekeeper synccopies them into datanew Ingresshost already used? deny
Figure 4. Referential policies need to see other objects, so Gatekeeper syncs them into OPA's data first.
Swipe sideways to see all of it, or tap to open it full screen.

Mutation

Gatekeeper's mutation CRDs change objects at admission:

  • Assign — set a field (e.g. securityContext.runAsNonRoot: true, default imagePullPolicy).
  • AssignMetadata — add labels/annotations (only additions).
  • ModifySet — add/remove items in lists (e.g. drop NET_RAW capability).
  • AssignImage — rewrite image registries/tags.

Mutation is powerful but can surprise developers ("my manifest says X but the cluster has Y") and makes GitOps diffs noisy. Keep mutations minimal, documented, and prefer validation with good messages.

Enlarge diagrampod without settingsAssign /AssignMetadataadd runAsNonRoot,labelsvalidationnow passes
Figure 5. Mutation fixes objects on the way in, then validation checks them.
Swipe sideways to see all of it, or tap to open it full screen.

Testing Gatekeeper policies

  • gator CLI: gator test evaluates resources against templates and constraints offline; gator verify runs suites of test cases — run it in CI on the policy repo.
  • Deploy to a non-prod cluster in dryrun and read audit results before enforcing.