Apply custom Pod-level security policies using Gatekeeper Stay organized with collections Save and categorize content based on your preferences.
This page shows you how to use the Gatekeeper admission controller to applyPod-level security controls to your Google Kubernetes Engine (GKE) clusters.On this page, you learn how to use Gatekeeper to apply constraints thatlet you apply security policies to help you meet security requirements for yourorganization.
This page is for Security specialists who want to apply security controlsto their GKE clusters. To learn more aboutcommon roles and example tasks that we reference in Google Cloud content, seeCommon GKE user roles and tasks.
Before reading this page, ensure that you're familiar with the following concepts:
- General overview of Gatekeeper.
- General overview of Open Policy Agent (OPA), which is used by Gatekeeper.
Gatekeeper overview
Gatekeeper is anadmission controller that validates requests to create and update Pods onKubernetes clusters, using the Open Policy Agent (OPA).
Using Gatekeeper allows administrators to define policies with aconstraint,which is a set of conditions that permit or deny deployment behaviors inKubernetes. You can then enforce these policies on a cluster using aConstraintTemplate. This document provides examples for restricting thesecurity capabilities of workloads to ensure enforce, test, and audit securitypolicies using Gatekeeper.
Gatekeeper can also:
- Roll out policies: Enforce policy in a gradual, scoped manner to limitthe risk of disrupting workloads.
- Dry-run policy changes: Provide mechanisms for testing policy impact andrange prior to enforcement.
- Audit existing policies: Ensure the application of security controls tonew and existing workloads (audit controls).
Key Gatekeeper concepts
Gatekeeper introduces two concepts in order to provide administrators with apowerful and flexible means of controlling their cluster:constraints, andconstraint templates, both of which are concepts inherited from the OpenPolicy AgentConstraint Framework.
Constraints are the representation of your security policy—they define therequirements and range of enforcement.Constraint templates are reusablestatements (written inRego)that apply logic to evaluate specific fields in Kubernetes objects, based onrequirements defined in constraints.
For example, you might have a constraint that declares allowable seccompprofiles that can be applied to Pods in a specific namespace, and a comparableconstraint template that provides the logic for extracting these values andhandling enforcement.
The following constraint template, from theGatekeeper repository,checks for the existence ofsecurityContext.privileged in a Pod specification:
apiVersion:templates.gatekeeper.sh/v1beta1kind:ConstraintTemplatemetadata:name:k8spspprivilegedcontainerspec:crd:spec:names:kind:K8sPSPPrivilegedContainertargets:-target:admission.k8s.gatekeeper.shrego:|package k8spspprivilegedviolation[{"msg": msg, "details": {}}] {c := input_containers[_]c.securityContext.privilegedmsg := sprintf("Privileged container is not allowed: %v, securityContext: %v", [c.name, c.securityContext])}input_containers[c] {c := input.review.object.spec.containers[_]}input_containers[c] {c := input.review.object.spec.initContainers[_]}To extend the previous constraint template example, the following constraint defines thescope (kinds) for the specific enforcement of this constraint template in adryrun mode:
apiVersion:constraints.gatekeeper.sh/v1beta1kind:K8sPSPPrivilegedContainermetadata:name:psp-privileged-containerspec:enforcementAction:dryrunmatch:kinds:-apiGroups:[""]kinds:["Pod"]With Gatekeeper, you can create your own constraints and constraint templates tomeet your specific needs. You can also use astandard set of constraints and constraint templates in theGatekeeper repository that have been defined to enable quick adoption and security enforcement. Eachconstraint is also accompanied with example Pod configurations.
Google Cloud provides a managed, officially supported version of open source Gatekeeper namedPolicy Controller. Google doesn't officially support the open source Gatekeeper project.
Before you begin
Before you start, make sure that you have performed the following tasks:
- Enable the Google Kubernetes Engine API. Enable Google Kubernetes Engine API
- If you want to use the Google Cloud CLI for this task,install and theninitialize the gcloud CLI. If you previously installed the gcloud CLI, get the latest version by running the
gcloud components updatecommand. Earlier gcloud CLI versions might not support running the commands in this document.Note: For existing gcloud CLI installations, make sure to set thecompute/regionproperty. If you use primarily zonal clusters, set thecompute/zoneinstead. By setting a default location, you can avoid errors in the gcloud CLI like the following:One of [--zone, --region] must be supplied: Please specify location. You might need to specify the location in certain commands if the location of your cluster differs from the default that you set.
Enable Gatekeeper on a cluster with Policy Controller
Policy Controlleris a policy engine built on theGatekeeper open source project. Googlerecommends the use of Policy Controller because it includes additional featuresto help enforce policy at scale, including policy-as-code,multi-cluster support, integration with Cloud Logging, and ability toview policy status in the Google Cloud console. Policy Controller is available withGKE, but you caninstall Gatekeeperon your cluster instead.
To enable Policy Controller on a cluster, follow thePolicy Controller installation guide.
Enable constraints and constraint templates
Gatekeeper and its constraint templates can beinstalled and enabled without adversely impacting existing or new workloads. Forthis reason, it's recommended that all applicable Pod security constrainttemplates be applied to the cluster.
Additionally, Gatekeeper constraints can be implemented to enforce controls forspecific objects, such as namespaces and Pods.
Observe the example below that limits the scope toPods located in theproduction namespace by defining them in the constraint match statement:
...spec: match: kinds: - apiGroups: [""] kinds: ["Pod"] namespaces: - "production"For more information about the available options forConstraint andConstraintTemplate objects, seeHow to use Gatekeeper.
Test policies
Introducing new policies to existing clusters can have adverse behavior, forexample by restricting existing workloads. One of the benefits of usingGatekeeper for Pod security is the ability to test the effectiveness and impacta policy will have without making actual changes, using a dry-run mode. Thisallows for policy configuration to be tested against running clusters withoutenforcement. Policy violations are logged and identified without interference.
The following steps demonstrate how a developer, operator, or administrator canapply constraint templates and constraints to determine their effectiveness orpotential impact:
Apply the Gatekeeper config for replicating data for audit and dry-runfunctionality:
kubectl create -f- <<EOFapiVersion:config.gatekeeper.sh/v1alpha1kind:Configmetadata:name:confignamespace:"gatekeeper-system"spec:sync:syncOnly:-group:""version:"v1"kind:"Namespace"-group:""version:"v1"kind:"Pod"EOFWith no constraints applied, run a workload with elevated privileges:
kubectl create -f- <<EOFapiVersion:v1kind:Podmetadata:name:nginxlabels:app:nginxspec:containers:-name:nginximage:nginxsecurityContext:privileged:trueEOFLoad the previous
k8spspprivilegedcontainerconstraint template:kubectl create -f- <<EOFapiVersion:templates.gatekeeper.sh/v1beta1kind:ConstraintTemplatemetadata:name:k8spspprivilegedcontainerspec:crd:spec:names:kind:K8sPSPPrivilegedContainertargets:-target:admission.k8s.gatekeeper.shrego:|package k8spspprivilegedviolation[{"msg": msg, "details": {}}] {c := input_containers[_]c.securityContext.privilegedmsg := sprintf("Privileged container is not allowed: %v, securityContext: %v", [c.name, c.securityContext])}input_containers[c] {c := input.review.object.spec.containers[_]}input_containers[c] {c := input.review.object.spec.initContainers[_]}EOFCreate a new constraint to extend this constraint template. Thistime, set the
enforcementActiontodryrun:kubectl create -f- <<EOFapiVersion:constraints.gatekeeper.sh/v1beta1kind:K8sPSPPrivilegedContainermetadata:name:psp-privileged-containerspec:enforcementAction:dryrunmatch:kinds:-apiGroups:[""]kinds:["Pod"]EOFWith Gatekeeper synchronizing running object data, and passively checkingfor violations, confirm if any violations were found by checking the
statusof the constraint:kubectlgetk8spspprivilegedcontainer.constraints.gatekeeper.sh/psp-privileged-container-oyamlapiVersion: constraints.gatekeeper.sh/v1beta1kind: K8sPSPPrivilegedContainermetadata:... name: psp-privileged-container...spec: enforcementAction: dryrun match: kinds: - apiGroups: - "" kinds: - Podstatus: auditTimestamp: "2019-12-15T22:19:54Z" byPod: - enforced: true id: gatekeeper-controller-manager-0violations: - enforcementAction:dryrun kind: Podmessage: 'Privileged container is not allowed: nginx, securityContext: {"privileged": true}' name: nginx namespace: defaultTo confirm that the policy doesn't interfere with deployments, run anotherprivileged Pod:
kubectl create -f- <<EOFapiVersion:v1kind:Podmetadata:name:privpodlabels:app:privpodspec:containers:-name:nginximage:nginxsecurityContext:privileged:trueEOFThis new Pod will be successfully deployed.
To clean up the resources created in this section, run the following commands:
kubectldeletek8spspprivilegedcontainer.constraints.gatekeeper.sh/psp-privileged-containerkubectldeleteconstrainttemplatek8spspprivilegedcontainerkubectldeletepod/nginxkubectldeletepod/privpod
Enforce policies
Now that you can confirm the validity and impact of a policy without impactingexisting or new workloads, you can implement a policy with full enforcement.
Building on the examples used to validate the policy above, the following stepsdemonstrate how a developer, operator, or administrator can apply constrainttemplates and constraints to enforce a policy:
Load the
k8spspprivilegedcontainerconstraint template mentioned earlier:kubectl create -f- <<EOFapiVersion:templates.gatekeeper.sh/v1beta1kind:ConstraintTemplatemetadata:name:k8spspprivilegedcontainerspec:crd:spec:names:kind:K8sPSPPrivilegedContainertargets:-target:admission.k8s.gatekeeper.shrego:|package k8spspprivilegedviolation[{"msg": msg, "details": {}}] {c := input_containers[_]c.securityContext.privilegedmsg := sprintf("Privileged container is not allowed: %v, securityContext: %v", [c.name, c.securityContext])}input_containers[c] {c := input.review.object.spec.containers[_]}input_containers[c] {c := input.review.object.spec.initContainers[_]}EOFCreate a new constraint to extend this constraint template. Thistime, don't set the
enforcementActionkey. By default, theenforcementActionkey is set todeny:kubectl create -f- <<EOFapiVersion:constraints.gatekeeper.sh/v1beta1kind:K8sPSPPrivilegedContainermetadata:name:psp-privileged-containerspec:match:kinds:-apiGroups:[""]kinds:["Pod"]EOFAttempt to deploy a container that declares privileged permissions:
kubectl create -f- <<EOFapiVersion:v1kind:Podmetadata:name:nginxlabels:app:nginxspec:containers:-name:nginximage:nginxsecurityContext:privileged:trueEOFThe following error message should be received:
Error from server ([denied by psp-privileged-container] Privileged container is not allowed:nginx, securityContext: {"privileged": true}): error when creating "STDIN": admission webhook "validation.gatekeeper.sh" denied the request: [denied by psp-privileged-container]Privileged container is not allowed: nginx, securityContext: {"privileged": true}To clean up, run the following commands:
kubectldeletek8spspprivilegedcontainer.constraints.gatekeeper.sh/psp-privileged-containerkubectldeleteconstrainttemplatek8spspprivilegedcontainer
Alternatives to Gatekeeper
Gatekeeper lets you declare and apply custom Pod-level security policies. Youcan also use Kubernetes' built-inPodSecurity admission controllerto apply predefined Pod-level security policies. These predefined policies arealigned with the levels defined by thePod Security Standards.
What's next
Gatekeeper provides an incredibly powerful means to enforce and validatesecurity on GKE clusters using declarative policies. Gatekeeper'suse extends beyond security however, and can be used in other aspects ofadministration and operations.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.