Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 588 of 8028. Security and ObservabilityFree lesson

Enforcing Security Policies with Admission Controllers

Utilize Policy Engines like OPA Gatekeeper or Kyverno to enforce governance policies that prevent non-compliant resources from being created in the cluster.

In this lesson, you will learn how to automate cluster governance and block non-compliant configurations before they ever reach your Kubernetes etcd database using policy engines like OPA Gatekeeper or Kyverno.

The Role of Admission Controllers

When you run kubectl apply, the request passes through an Admission Controller pipeline. While Kubernetes has built-in controllers (like NamespaceLifecycle), they are often insufficient for organizational security. Policy engines act as "Dynamic Admission Controllers," intercepting API requests to validate them against custom business logic. If a request violates your policy, the engine rejects it, preventing the resource from being created.

Example: Enforcing Image Registries

Suppose you want to ensure that all developers only pull container images from your company’s private registry (e.g., company-registry.io). Instead of manually checking every deployment, you can define a policy. Using Kyverno, a policy looks like this:

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: restrict-image-registry
spec:
  validationFailureAction: Enforce
  rules:
  - name: check-image-registry
    match:
      resources:
        kinds:
          - Pod
    validate:
      pattern:
        spec:
          containers:
          - image: "company-registry.io/*"

When a user tries to deploy a pod with an image from docker.io or another public source, the Kyverno controller intercepts the request, evaluates the rule, and returns a 403 Forbidden error to the user.

Why Use Policy Engines?

  1. Shift-Left Security: You stop bad configurations (like running as root, missing resource limits, or using insecure registries) at the entry point.
  2. Declarative Governance: Policies are written as YAML, allowing you to manage them via GitOps just like your application code.
  3. Auditability: These tools provide status reports, showing which resources in your cluster are currently out of compliance, helping you identify technical debt without breaking existing workloads.

By integrating these tools, you transform your cluster from a "trust-based" environment into a "verified-policy" environment where compliance is enforced automatically.

Key Takeaway: Admission controllers provide a powerful gatekeeping mechanism that intercepts API requests, allowing policy engines to block non-compliant resources and ensure your cluster maintains a predefined security posture.