Gatekeeper

Gatekeeper extends OPA into Kubernetes as a policy enforcement engine that blocks non-compliant workloads before they are created. It integrates directly with Kubernetes admission control and applies Compliance as Code across namespaces and clusters. Gatekeeper enforces best practices, governance standards, security controls, and compliance rules using policies written in Rego.

What Gatekeeper Does

Gatekeeper intercepts API requests during the admission phase and evaluates them against defined constraints. It enforces:

• security baselines
• governance standards
• naming and labeling conventions
• resource quotas
• image registry restrictions
• pod hardening guidelines
• compliance rules for deployments
• infrastructure guardrails

It ensures no workload can enter the cluster unless it passes defined policies.

Gatekeeper also runs in audit mode, scanning existing cluster objects for violations.

Core Concepts of Gatekeeper

Gatekeeper uses two main components:

ConstraintTemplate

Defines the policy logic using Rego.
It includes:

• schema
• parameters
• rego rule
• violation output

ConstraintTemplates create new policy types.

Constraint

Instance of a policy created from a ConstraintTemplate.
It defines:

• scope
• match rules
• namespaces
• parameters
• enforcement mode

Constraints decide which resources a rule applies to.

Gatekeeper Admission Flow

  1. User submits Kubernetes manifest

  2. API server passes the request to Gatekeeper

  3. Gatekeeper loads ConstraintTemplates and Constraints

  4. Rego policy evaluates manifest

  5. If violations exist, request is denied

  6. If compliant, object is created

Gatekeeper ensures invisible but strict governance.

Why Gatekeeper Matters in DevSecOps

Gatekeeper enforces security before deployment. It prevents:

• unsecured pods
• privilege escalation
• misconfigured workloads
• unapproved images
• missing labels
• insecure network policies
• drift from security baselines
• resource misuse

It reduces human review effort and eliminates misconfigurations at the source.

Common Gatekeeper Use Cases

• require non-root containers
• block privileged pods
• enforce image registry policies
• require labels like team, owner, cost-center
• block hostPath volumes
• require resource limits
• restrict namespace creation
• enforce mandatory annotations
• validate Ingress hostnames
• ensure TLS requirements
• enforce naming conventions

Gatekeeper becomes the governance engine of Kubernetes.


Full-Length Practical Section

Comprehensive, step-by-step hands-on tasks for using Gatekeeper in real clusters.


Practical 1: Install Gatekeeper in Kubernetes

kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml

Verify:

kubectl get pods -n gatekeeper-system

Practical 2: Create a ConstraintTemplate to Block Privileged Pods

Create file blockprivileged-template.yaml:

apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: blockprivileged
spec:
  crd:
    spec:
      names:
        kind: BlockPrivileged
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package blockprivileged

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

Apply:

kubectl apply -f blockprivileged-template.yaml

Practical 3: Create Constraint for the Template

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: BlockPrivileged
metadata:
  name: disallow-privileged
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]

Apply:

kubectl apply -f blockprivileged-constraint.yaml

Practical 4: Test the Privileged Pod Denial

Create pod:

apiVersion: v1
kind: Pod
metadata:
  name: test-priv
spec:
  containers:
    - name: c
      image: alpine
      securityContext:
        privileged: true
      command: ["sleep", "3600"]

Apply:

kubectl apply -f test-priv.yaml

Gatekeeper denies it.


Practical 5: Enforce Non-root Containers

ConstraintTemplate:

violation[{"msg": msg}] {
  sc := input.review.object.spec.containers[_].securityContext
  not sc.runAsNonRoot
  msg := "Containers must run as non-root"
}

Constraint matches Pods and Deployments.


Practical 6: Enforce Allowed Image Registry

violation[{"msg": msg}] {
  image := input.review.object.spec.containers[_].image
  not startswith(image, "registry.mycompany.com/")
  msg := "Image must come from approved registry"
}

Apply constraint to all namespaces except kube-system.


Practical 7: Require Mandatory Labels

Template:

violation[{"msg": msg}] {
  not input.review.object.metadata.labels.owner
  msg := "owner label is required"
}

Constraint:

• apply to all Deployments
• match namespace patterns starting with "dev-" or "prod-"


Practical 8: Enforce Resource Limits for CPU and Memory

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

This prevents unbounded containers.


Practical 9: Audit Existing Cluster Resources

kubectl get k8snonroot --all-namespaces -o yaml

Gatekeeper reports all objects violating rules.


Practical 10: Enable Gatekeeper Audit Mode

Audit mode scans existing cluster resources independently from admission control.

kubectl get constraints -A

Check status.violations.


Practical 11: Write Policy to Block hostPath Volume Usage

violation[msg] {
  vol := input.review.object.spec.volumes[_].hostPath
  msg := "hostPath volumes are prohibited"
}

Apply to StatefulSets and Pods.


Practical 12: Validate Ingress Domain Rules

violation[msg] {
  host := input.review.object.spec.rules[_].host
  not endswith(host, ".company.com")
  msg := "Ingress host must end with company.com"
}

Practical 13: Block Capabilities Additions

violation[msg] {
  cap := input.review.object.spec.containers[_].securityContext.capabilities.add[_]
  msg := sprintf("Adding capability %v is not allowed", [cap])
}

Practical 14: Enforce TLS on Ingress

violation[msg] {
  not input.review.object.spec.tls
  msg := "TLS is required for all Ingress resources"
}

Practical 15: Enforce PodSecurity Restricted Settings

Integrate policy that validates:

• allowPrivilegeEscalation: false
• readOnlyRootFilesystem: true
• drop all capabilities

Use Rego matching container securityContext.


Practical 16: Apply Gatekeeper Policies With GitOps

Push constraints to Git:

git add constraints/
git commit -m "add compliance policy"

Argo CD and Flux automatically apply them cluster-wide.


Practical 17: Validate Every Kubernetes YAML in CI/CD

kubectl apply --dry-run=client -o json -f deploy.yaml |
opa eval --data policies.rego --input - "data"

Fail pipeline when deny rules hit.


Practical 18: Export Gatekeeper Violations

View violations:

kubectl get constrainttemplates
kubectl describe constraint <name>

Export logs to SIEM for compliance reporting.


Practical 19: Auto-remediate Violations Via CI/CD

If audit detects drift:

• pipeline updates manifests
• redeploy corrected versions
• notify security team automatically


Practical 20: Build End-to-End Gatekeeper Architecture

Architecture includes:

• Gatekeeper admission controller
• ConstraintTemplates with Rego logic
• Constraints enforcing namespace-level, cluster-level, or object-level rules
• audit mode for cluster-wide drift detection
• CI/CD validation using OPA
• GitOps for policy delivery
• SIEM integration for violation reporting
• auto-remediation workflows
• strict enforcement for high-security clusters

This creates complete Compliance-as-Code enforcement for Kubernetes.


Intel Dump

• Gatekeeper integrates OPA with Kubernetes admission control
• enforces compliance before workloads are created
• uses ConstraintTemplates (policy logic) and Constraints (policy instances)
• blocks insecure pods, unapproved images, missing labels, hostPath volumes, and misconfigurations
• practicals covered installation, custom policies, registry enforcement, resource limits, audit mode, CI/CD validation, GitOps sync, violations export, and full Gatekeeper governance architecture

HOME LEARN COMMUNITY DASHBOARD