Kubernetes admission control with OPA Gatekeeper

Gatekeeper enforces organization policy on Kubernetes objects through Rego constraint templates. This page covers the constraint library, audit, mutation, dry-run rollout and how it compares with Kyverno and built-in CEL policies.

On this page

What OPA Gatekeeper does at admission and when teams need it

A platform team that runs self-managed Kubernetes clusters often needs to stop non-compliant workloads before they are stored, not after they are running. OPA Gatekeeper answers that need as a validating admission webhook. When a user or pipeline creates or updates an object, the Kubernetes API server sends the request to Gatekeeper, which evaluates it against policy and either allows or denies it. The policy logic is written in Rego, the language used by Open Policy Agent. Gatekeeper separates that logic into constraint templates, which define a reusable rule and its parameters, and constraints, which apply a template to specific resource kinds, namespaces and parameter values. A platform team can therefore ship one vetted template, such as one requiring labels or restricting image registries, and instantiate it differently for each environment.

Built-in Pod Security Admission covers a narrower job. It enforces the three Pod Security Standards (Privileged, Baseline and Restricted) per namespace, and it needs no extra components. Teams that only need those pod-level profiles may not need Gatekeeper at all. Gatekeeper fits when the rules go beyond the standards: required labels or owners, approved registries, mandatory resource limits, ingress host restrictions, or organization-specific naming. It also fits when one policy language must cover objects that Pod Security Admission does not inspect. Before choosing, confirm which Kubernetes version your clusters run and whether it meets the admission features you plan to use, since the supported minor versions are listed on the Kubernetes releases page.

Gatekeeper adds a webhook in the request path, so its availability and failure behavior matter as much as its rules. A broken or slow webhook can block deployments across the cluster, and the platform team owns that risk. Plan for replicas, resource requests, exemptions for system namespaces, and a tested recovery procedure before the first enforcing constraint goes live. Also decide who writes and approves templates, because Rego is a skill most platform teams must build or hire for. Kyverno and the built-in CEL-based validation in Kubernetes are alternatives with different authoring models, and the comparison later on this page covers how to choose between them.

How a request flows through Gatekeeper

The flow starts when a user or pipeline sends a change to the kube-apiserver, which first authenticates and authorizes the caller. Mutating webhooks run before validating webhooks, so Gatekeeper's admission webhook evaluates the object against active constraints only after the API server has accepted the request through its own checks. Gatekeeper pods sit outside the control plane, so the webhook call crosses a trust boundary. A separate audit loop rescans objects already stored in etcd and reports violations as constraint status, which is where you check for resources created before a policy existed.

Admission path through the API server and Gatekeeper, plus the audit loop over stored resources.

Constraint templates, constraints and the policy library

A ConstraintTemplate contains the policy logic. It defines a new custom resource kind, and the logic is written in Rego, the policy language used by Open Policy Agent. The template declares the schema of the parameters that a Constraint may pass in, and the Rego rule produces violations when a resource breaks the policy. Writing a template is a development task: it needs someone who can read Rego, test it and explain what it denies. Because the template defines a new kind, its installation changes the API surface of the cluster, so it should be reviewed like any other change to cluster configuration.

  • Rego logic: The violation rule returns a message for each resource that fails the check. Keep the rule small and name the check for what it tests, such as required labels or allowed image registries.
  • CRD generated from the template: Gatekeeper creates the custom resource definition from the template's name and parameter schema, so the template name becomes the kind used in Constraints.
  • Parameter schema: Declare every input a Constraint can set, with types, so invalid parameters fail early instead of silently passing.
  • Version control: Store templates in Git with their Rego tests so changes go through review before they reach the cluster.
  • Ownership: Name one team that maintains the template logic and approves changes.

Before installing any template, confirm the Gatekeeper release it targets and the Rego features it uses against the version running in your cluster.

Gatekeeper, Kyverno and built-in CEL policies compared

This table compares the three main ways to enforce admission rules on a self-managed cluster across language, mutation, audit, exceptions, operating footprint and team fit. Read each row against your team's skills and your release-note checks, since project features change between versions. The main takeaway is that the choice usually follows from whether your team already writes Rego or prefers YAML, and how much mutation you need.

CriterionOPA GatekeeperKyvernoBuilt-in CEL policies
Policy languageRego in ConstraintTemplates, with separate constraint objectsYAML policies with its own expression syntax, plus CEL support in newer versionsCEL expressions in ValidatingAdmissionPolicy objects, no extra controller required
Mutation supportMutation through Assign and related mutation resources; confirm current scopeMutate and generate rules are core featuresMutating admission policies exist in newer releases; confirm availability on your version
Audit reportingAudit controller reports violations on existing resources in constraint statusPolicy reports generated for existing resourcesValidation results visible through the API server; check for reporting depth in your version
Exception handlingTypically handled through match scoping and namespace exclusions in configExceptions as dedicated custom resourcesHandled through match conditions and parameter resources; plan exceptions explicitly
Operational footprintController and audit pods to run, upgrade and monitorController set to run, upgrade and monitor; more resources to manageNo additional controller; relies on API server feature gates and version
Fit for Rego teamsStrong fit if your team already reviews and tests RegoWeaker fit, since rules are written in YAMLWeaker fit for Rego teams; CEL is a different language
Fit for YAML-first teamsRequires learning Rego before writing rulesStrong fit; rules sit alongside manifestsGood fit for simple validation rules written in YAML
Confirm before adoptingCurrent Gatekeeper release notes for mutation and audit changesCurrent Kyverno release notes for CEL, exception and report changesAPI server version and feature gate status for your cluster

Installing Gatekeeper and rolling out policy safely

This sequence takes Gatekeeper from a working installation to enforced policy without blocking workloads the cluster needs. Each step ends with a check, so a failure is caught while only audit results or warnings are affected.

  1. Mirror Gatekeeper images to the private registry

    Pull the Gatekeeper controller and audit images from the upstream project, verify them, and push them to your private registry. Configure the image repository in the Helm values or manifests so the pods pull only from that registry. Remember that private registry configuration applies to the whole cluster: if you use kubeadm, the same kind of setting (for example, kubeadm config images list and pull, and --image-repository on kubeadm init) governs the control plane images, and node runtimes need trust for the registry too. Done when every Gatekeeper pod reaches Running with images pulled from your registry, with no outbound pulls in the logs.

  2. Install Gatekeeper and confirm webhook health

    Install the Gatekeeper controller and audit components into a dedicated namespace that is excluded from its own policies. Review the validating webhook configuration and set the failure policy deliberately: a fail-closed setting blocks all admitted requests if Gatekeeper is down, while fail-open lets requests through. Confirm the webhook endpoint responds and that the API server can reach it on the Gatekeeper service. Done when the webhook is registered, its service has ready endpoints, and a test resource in an unlabeled namespace is admitted normally.

  3. Deploy constraint templates from your library

    Apply ConstraintTemplate resources that define the Rego logic for each rule, starting with a short list such as required labels, allowed image registries, and disallowed privileged containers. Keep templates in Git alongside their tests so changes are reviewed. Ask your security team to confirm which control requirements each template maps to before anything is enforced. Done when Gatekeeper reports each template as created, and the generated constraint CRDs appear in the API server.

  4. Start constraints in warn or dryrun mode

    Create the constraint objects with enforcementAction set to warn or dryrun, scoped by namespace and match rules to the workloads you intend to govern. Start with one rule and a narrow scope. Platform namespaces such as kube-system and your GitOps controllers should be excluded through match configuration or the process exemption list. Done when a test pod that violates the rule is admitted with a warning or recorded only, and the constraint status shows it is active.

  5. Review audit results against existing resources

    Gatekeeper's audit function periodically evaluates existing resources against each constraint and writes violations into the constraint status. Export the violation lists, group them by namespace and owner, and decide for each one whether to fix the workload, add a documented exception, or accept the finding for a timed window. Confirm with application owners before anything is changed. Done when every violation for the constraint has a recorded disposition and the remaining list is either empty or explicitly accepted.

  6. Fix violations and rerun the audit

    Work through the owners' fixes in Git, then let the audit cycle run again and confirm the violation count drops as expected. Where a rule is too broad, adjust the template parameters or the match scope and rerun the tests in the repository. Keep the warn or dryrun setting until the list is stable across several audit results. Done when the violation count for the constraint matches the accepted exceptions and no unexpected namespaces appear in the report.

  7. Switch constraints to deny and monitor

    Change enforcementAction to deny for each constraint in turn, starting with the rules that had the fewest violations. Apply the change through the same Git workflow, and watch admission denials and the webhook's health and latency during the change. Be ready to revert the single constraint to warn if a legitimate deployment is blocked. Done when new non-compliant resources are rejected with a clear message, the webhook stays healthy, and the constraint's deny decisions appear in your logs and dashboards.

How audit of existing resources and mutation fit the rollout

Audit is the step that tells you how much remediation a constraint will cause before you turn it into enforcement. Gatekeeper's audit function periodically evaluates the resources already stored in the cluster against each constraint and records violations in the status of the constraint objects, without blocking anything. Run a constraint in dryrun mode first, read the violation list per namespace, and sort the results into three groups: workloads owned by teams that can fix them quickly, platform components that will need an exception, and resources that are simply stale. The size of the first group is what sets the enforcement date. Confirm with your Gatekeeper version how audit interval and violation reporting are configured, since audit results are only as current as the last run, and check whether your team will read them from the constraint status or export them to a dashboard.

Mutation is a separate capability with its own risks, and it deserves a separate decision. Mutation policies such as Assign and ModifySet change objects as they are admitted, for example to add a missing label, set securityContext fields or pin imagePullPolicy. The danger is that the change happens silently: the author submits one manifest, the cluster stores another, and a later kubectl diff or GitOps sync shows drift that nobody expected. Mutations also run alongside other mutating admission webhooks, and the order in which they apply is not something to assume. Before enabling a mutation, list every other webhook in the cluster that mutates the same fields, test the combined result on a non-production cluster, and decide whether the change should be surfaced to the author through documentation or a validation rule that rejects the unmutated form instead.

Security and operational risks of admission webhooks

Gatekeeper runs as a validating and mutating webhook inside the API request path, so a policy mistake can block workloads or weaken controls across the whole cluster. The cards below cover the risks that matter most in production and the control for each one.

Webhook failure policy and lockout

If the webhook is unreachable and its failure policy is set to Fail, the API server rejects matching requests, which can stop deployments, scaling and even recovery work. Check the failure policy for each webhook configuration, confirm how many replicas serve the webhook, and decide which namespaces must stay outside its scope so a broken pod cannot block the fix for itself. Test an outage in a non-production cluster before go-live.

Authentication docs

Gatekeeper service account RBAC

Gatekeeper reads many resource types to evaluate policies and writes status and audit results back to constraints. An overly broad cluster role gives the controller a path to change workloads it does not need to touch. Review the generated ClusterRole and bindings, limit write verbs to the objects Gatekeeper must update, and restrict who can edit the Gatekeeper deployment and its service account.

Namespace exemptions for system components

Exempting namespaces such as kube-system from constraints avoids blocking core components, but every exemption is a gap in enforcement. Keep the exemption list short and written down, tie each entry to a named component, and confirm that exempted namespaces still get review through other controls such as Pod Security Admission. Revisit the list whenever a new platform add-on is installed.

Rego test coverage

A Rego template that compiles can still allow or deny the wrong resources. Write unit tests with opa test for allowed and denied inputs, including edge cases such as missing labels, init containers and default values. Run those tests in CI on every change to a template or constraint so a logic error is caught before it reaches the admission path.

Exception governance

Teams often ask for one-off exceptions to unblock releases, and exceptions that never expire become permanent policy changes. Record each exception with an owner, a reason, a scope and an expiry date, and store it in version control alongside the constraints. Review open exceptions on a fixed schedule and remove any that no longer have a current owner or reason.

Audit trail of policy changes

Constraint and template changes alter what the cluster allows, so you need to know who changed what and when. Enable Kubernetes audit logging for changes to ConstraintTemplate and constraint resources, forward those logs to storage the platform team cannot silently edit, and tie each change to a reviewed merge request. Confirm retention with your compliance owner before choosing a period.

Questions teams ask before running Gatekeeper

What drives the effort of a Gatekeeper rollout?

The effort is driven mostly by how many policies you enforce, how much of your existing cluster state already violates them, and how many teams must change their manifests before enforcement. A small set of constraints from a standard library, applied to a few namespaces, is far less work than a full organization policy set with custom Rego templates, mutation rules and exceptions for platform workloads. Other drivers include how many clusters run the policies, how well your policy owners agree on what is allowed, and whether the team maintains policies in Git with tests. Ask any partner to break the quote down by policy count, cluster count, custom template count and the audit and dry-run phases.

Can our own team run a Gatekeeper rollout without outside help?

Yes, if your team already operates Kubernetes clusters, can write and test Rego, and has policy owners who can decide what is allowed. The skills that are often missing are Rego testing, a habit of running audit before enforcement, and the discipline to keep exceptions documented. Teams without these skills usually spend the most time on the first constraint templates and on untangling existing violations. A partner is most useful for designing the constraint library, setting up the audit and dry-run process, and handing over tests and runbooks. Whichever path you choose, make sure at least two engineers can change and roll back a constraint without the person who wrote it.

How long does a Gatekeeper pilot take?

The length of a pilot depends on scope rather than on a fixed number of weeks. The main inputs are the number of clusters in the pilot, how many policies are in the first set, how much existing workload must be reviewed in audit mode, and how quickly the teams that own those workloads can respond to findings. A pilot on one non-production cluster with three or four constraints moves much faster than a pilot that spans production clusters with several custom templates. Ask for a timeline tied to named milestones such as audit baseline, first enforcement namespace and exception review, and confirm which of those depend on your teams' availability.

Can Gatekeeper and Kyverno run in the same cluster?

They can be installed together because both act as validating and mutating admission webhooks, but running two policy engines on the same resources adds risk and complexity. Overlapping rules can produce conflicting decisions, duplicate audit findings and harder troubleshooting when a deployment is rejected. If you already have one engine in production, the usual approach is to keep it for the existing rule set and avoid writing new rules for the same resources in the other engine. Before you decide, confirm which resource kinds each engine will govern, how their webhook failure policies are set, and who is responsible for each rule set. Our Kubernetes policy as code with Kyverno planning is a separate topic that covers the same engine choice in more depth.

What does the work need from our side?

The work needs access to the target clusters, named policy owners who can approve rules and exceptions, and test namespaces where enforcement can be tried before production. In practice this means a service account or kubeconfig with rights to install the controller and read cluster state, a Git repository for policies and tests, and a change window for enabling enforcement. Policy owners from security, platform and the main application teams should be available for review sessions, because most rework comes from rules that nobody agreed on. Also confirm where images for the controller and policy library will be pulled from if the clusters have no internet access, since the install depends on it.

What does a fixed-scope Gatekeeper engagement cover?

A fixed-scope engagement covers the scope, deliverables and timeline agreed in writing before work starts. For Gatekeeper, that scope usually lists the clusters, the constraint library and any custom Rego templates, the audit baseline, the mutation rules if they are included, the dry-run and enforcement plan, the exception process, and the handover of tests and runbooks. Anything outside the agreed list, such as new clusters, additional engines or policies added later, is handled as a change to the written scope. Ask for the list of deliverables and acceptance checks in the proposal so you can compare it directly with what your own team would produce.

What should we check before enforcing a new constraint?

Check that the constraint has run in audit or dry-run mode long enough to show every existing violation, that each violation has an owner and a fix or an approved exception, and that the constraint has tests covering both allowed and rejected manifests. Also confirm the failure policy of the admission webhook, because a broken controller can block deployments if it fails closed. Finally, check that the platform namespaces that run the controller itself are excluded, so the policy engine cannot lock out its own recovery. Record each check so an auditor or a new team member can see when and why enforcement was turned on.

How DeployOpen scopes a Gatekeeper policy engagement

A Gatekeeper engagement starts with a written scope that names the parts of the work so both sides can see what is included. In practice the scope usually lists the target clusters where constraints will be enforced, the policy catalog (which constraint templates and constraints are in use, which are custom Rego, and which are mutation rules), the audit findings from existing resources that must be remediated or formally excepted, the exception process for platform workloads such as system namespaces and cluster add-ons, and the test suite that proves each constraint allows and denies what it should. It also records which namespaces run in dry-run or warn mode first, who approves the move to enforcement, and who owns the policy repository after handover. Ask for each of these items to be written down, because an unnamed item usually turns into unplanned work later.

DeployOpen does not publish a price list. The quote follows from the written scope, so the cost of an engagement depends on the number of clusters, how many policies are custom compared with taken from the library, how much existing workload content needs remediation, the number of exception paths to design, and whether the test suite and the operating handover are included. Ask the quote to separate one-time build work from any recurring support or upgrade retainer, and confirm which Gatekeeper versions the scope covers, since the Gatekeeper project's own release and support cycle may differ from Kubernetes releases. Confirm with your own platform team which clusters and namespaces are in scope before requesting a quote.

How DeployOpen works on this

DeployOpen treats Gatekeeper as a policy program rather than a one-time install. We start with the rules your organization needs, run them in audit mode against the cluster you already have, and move to enforcement only after the findings are triaged and the exceptions are documented.

How we scope

  • Inventory the clusters, namespaces and workload owners the admission policies will cover.
  • Agree the constraint library in writing, with each policy mapped to an organization requirement.
  • Define which resources are audited first, which are enforced later, and who approves exceptions.
  • Engagements are fixed-scope, with deliverables and timelines agreed before work starts.

How we build

  • Install Gatekeeper in your clusters from images you can pull inside your own network.
  • Write or adapt ConstraintTemplates in Rego and test them against sample manifests in Git.
  • Configure audit runs, review violations with platform and application owners, and fix the top causes.
  • Introduce dry-run and warn modes before enforcement, and document any mutation rules you add.

How we hand over

  • Deliver the policy repository with templates, constraints, tests, exception records and rollout notes.
  • Document how to read audit results, add a constraint and request an exception.
  • Walk your platform team through the decision record on Gatekeeper, Kyverno and built-in CEL policies.
  • Confirm with your team which tests run in CI and who owns each policy after handover.

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers.
  • Review Gatekeeper version changes and Kubernetes upgrade effects on existing constraints.
  • Re-run audits on a schedule you set and report new violations to the owning teams.
  • Confirm with your vendor and your own environment which Gatekeeper release fits your Kubernetes version.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.