Skip to content

Gatekeeper Cheat Sheet

- :material-content-copy: **Copy Commands** --- - :material-file-pdf-box: **Generate PDF** ---

Installation and Setup

Install Gatekeeper

# Install latest Gatekeeper
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/release-3.14/deploy/gatekeeper.yaml

# Verify installation
kubectl get pods -n gatekeeper-system
kubectl get crd | grep gatekeeper

Check System Status

# Check all Gatekeeper components
kubectl get all -n gatekeeper-system

# View Gatekeeper configuration
kubectl get config -n gatekeeper-system -o yaml

# Check webhook configuration
kubectl get validatingadmissionconfiguration gatekeeper-validating-admission-configuration

Constraint Templates

Create Constraint Template

# constraint-template.yaml
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
      validation:
        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 := input.review.object.metadata.labels
          missing := required[_]
          not provided[missing]
          msg := sprintf("Missing required label: %v", [missing])
        }

Apply Template

# Apply constraint template
kubectl apply -f constraint-template.yaml

# List all constraint templates
kubectl get constrainttemplates

# View template details
kubectl describe constrainttemplate k8srequiredlabels

Constraints

Create Constraint

# constraint.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: must-have-environment
spec:
  match:
    kinds:
      - apiGroups: ["apps"]
        kinds: ["Deployment"]
    namespaces: ["production"]
  parameters:
    labels: ["environment", "team", "version"]

Manage Constraints

# Apply constraint
kubectl apply -f constraint.yaml

# List all constraints
kubectl get constraints

# View constraint status
kubectl get k8srequiredlabels must-have-environment -o yaml

# Check violations
kubectl describe k8srequiredlabels must-have-environment

Policy Examples

Required Labels Policy

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
      validation:
        properties:
          labels:
            type: array
            items:
              type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequiredlabels

        violation[{"msg": msg}] {
          required := input.parameters.labels
          provided := input.review.object.metadata.labels
          missing := required[_]
          not provided[missing]
          msg := sprintf("Missing required label: %v", [missing])
        }

Resource Limits Policy

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8scontainerlimits
spec:
  crd:
    spec:
      names:
        kind: K8sContainerLimits
      validation:
        properties:
          cpu:
            type: string
          memory:
            type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8scontainerlimits

        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          not container.resources.limits.cpu
          msg := "Container must have CPU limits"
        }

        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          not container.resources.limits.memory
          msg := "Container must have memory limits"
        }

Security Context Policy

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8ssecuritycontext
spec:
  crd:
    spec:
      names:
        kind: K8sSecurityContext
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8ssecuritycontext

        violation[{"msg": msg}] {
          input.review.object.spec.securityContext.runAsRoot == true
          msg := "Containers must not run as root"
        }

        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          container.securityContext.privileged == true
          msg := "Privileged containers are not allowed"
        }

Configuration Management

Sync Configuration

# sync-config.yaml
apiVersion: config.gatekeeper.sh/v1alpha1
kind: Config
metadata:
  name: config
  namespace: gatekeeper-system
spec:
  sync:
    syncOnly:
      - group: ""
        version: "v1"
        kind: "Namespace"
      - group: "apps"
        version: "v1"
        kind: "Deployment"
  validation:
    traces:
      - user:
          kind:
            group: "*"
            version: "*"
            kind: "*"

Exclude Namespaces

apiVersion: config.gatekeeper.sh/v1alpha1
kind: Config
metadata:
  name: config
  namespace: gatekeeper-system
spec:
  match:
    - excludedNamespaces: ["kube-system", "gatekeeper-system"]
      processes: ["*"]

Mutation Policies

Assign Mutation

# assign-mutation.yaml
apiVersion: mutations.gatekeeper.sh/v1alpha1
kind: Assign
metadata:
  name: add-security-label
spec:
  applyTo:
    - groups: ["apps"]
      kinds: ["Deployment"]
      versions: ["v1"]
  match:
    scope: Namespaced
    kinds:
      - apiGroups: ["apps"]
        kinds: ["Deployment"]
  location: "metadata.labels.security-scan"
  parameters:
    assign:
      value: "required"

AssignMetadata Mutation

# assignmetadata-mutation.yaml
apiVersion: mutations.gatekeeper.sh/v1alpha1
kind: AssignMetadata
metadata:
  name: add-annotation
spec:
  match:
    scope: Namespaced
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
  location: "metadata.annotations.gatekeeper"
  parameters:
    assign:
      value: "mutated"

Data Replication

Provider Configuration

# provider-config.yaml
apiVersion: externaldata.gatekeeper.sh/v1alpha1
kind: Provider
metadata:
  name: image-scanner
spec:
  url: https://image-scanner.example.com/scan
  timeout: 30

External Data Template

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8simagescan
spec:
  crd:
    spec:
      names:
        kind: K8sImageScan
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8simagescan

        violation[{"msg": msg}] {
          image := input.review.object.spec.containers[_].image
          response := external_data({"provider": "image-scanner", "keys": [image]})
          response[image].vulnerabilities > 0
          msg := sprintf("Image %v has vulnerabilities", [image])
        }

Monitoring and Troubleshooting

Check Violations

# View constraint violations
kubectl get <constraint-kind> <constraint-name> -o yaml

# Check audit logs
kubectl logs -n gatekeeper-system -l control-plane=audit-controller

# View webhook logs
kubectl logs -n gatekeeper-system -l control-plane=controller-manager

# Check metrics
kubectl port-forward -n gatekeeper-system svc/gatekeeper-controller-manager-metrics-service 8080:8080
curl localhost:8080/metrics

Debug Policies

# Test constraint template
kubectl apply --dry-run=server -f test-resource.yaml

# View constraint status
kubectl describe constraint <constraint-name>

# Check template compilation
kubectl get constrainttemplate <template-name> -o yaml

Emergency Procedures

Disable Gatekeeper

# Disable admission webhook
kubectl delete validatingadmissionconfiguration gatekeeper-validating-admission-configuration

# Set webhook to ignore failures
kubectl patch validatingadmissionconfiguration gatekeeper-validating-admission-configuration \
  --type='merge' \
  -p='{"webhooks":[{"name":"validation.gatekeeper.sh","failurePolicy":"Ignore"}]}'

Recovery Operations

# Remove all constraints
kubectl delete constraints --all

# Remove constraint templates
kubectl delete constrainttemplates --all

# Restart Gatekeeper
kubectl rollout restart deployment/gatekeeper-controller-manager -n gatekeeper-system
kubectl rollout restart deployment/gatekeeper-audit -n gatekeeper-system

Best Practices

Policy Development

  • Start with warn enforcement mode
  • Test policies in development environments
  • Use descriptive violation messages
  • Implement gradual rollout strategies

Performance Optimization

  • Limit constraint scope with match criteria
  • Use efficient Rego policies
  • Monitor resource usage
  • Implement proper caching strategies

Security Considerations

  • Regularly update Gatekeeper
  • Monitor for policy bypasses
  • Implement proper RBAC
  • Audit policy changes