Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 726 of 80210. Deployment Strategies and GitOpsFree lesson

Enforce Cluster Security with Open Policy Agent

Implement OPA Gatekeeper to define and enforce security policies that automatically reject non-compliant manifest deployments within your GitOps pipeline.

In this lesson, you will learn how to integrate Open Policy Agent (OPA) Gatekeeper into your GitOps pipeline to automatically block non-compliant manifest deployments before they ever reach your cluster state.

While GitOps tools like ArgoCD or Flux are excellent at reconciling your desired state with the actual cluster state, they don’t natively stop a developer from committing a "dangerous" manifest—such as one that runs a container as root. OPA Gatekeeper acts as an admission controller that intercepts these requests, evaluates them against defined Rego policies, and rejects them if they violate your security posture.

The Workflow: Guardrails at the Edge

When you move to a mature GitOps model, you want to shift your security "left." Instead of discovering a security misconfiguration after the GitOps controller has already synced it to your production cluster, you want the deployment to fail during the validation phase.

To implement this, you define ConstraintTemplates (the logic) and Constraints (the enforcement). For example, to prevent containers from running as root, you would deploy a policy that evaluates the securityContext:

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPRootUser
metadata:
  name: must-run-as-non-root
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]

GitOps Integration

When your GitOps engine attempts to apply a manifest that violates this Constraint, the Kubernetes API server will reject the request. The GitOps operator will then report an OutOfSync status, accompanied by a clear error message explaining why the deployment was denied. This creates a tight feedback loop: the developer sees the error in the GitOps dashboard immediately, knows exactly which security rule was triggered, and can fix the manifest in the source repository.

This approach ensures that even if a developer accidentally commits a configuration that circumvents your security best practices, the cluster remains protected by an immutable, automated gatekeeper that treats security policies as code.

Key Takeaway: By implementing OPA Gatekeeper in your GitOps workflow, you transition from reactive security auditing to proactive, automated enforcement that prevents insecure configurations from ever becoming the cluster's reality.