Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 500 of 8027. Package Management and AutomationFree lesson

Enforcing Policy as Code with OPA Gatekeeper

Integrate Open Policy Agent with your deployment pipelines to automatically validate Helm charts against security and compliance standards before execution.

In this lesson, you will learn how to shift your OPA Gatekeeper security policies "left" by integrating them directly into your CI/CD pipelines to validate Helm charts before they ever reach the cluster.

The Problem: Reactive vs. Proactive Compliance

While OPA Gatekeeper typically runs as an Admission Controller inside Kubernetes, waiting until deployment to catch a violation is often too late. If a developer pushes a Helm chart that ignores your security standards—such as running containers as root—the deployment will be rejected by the cluster, causing a failed CI/CD pipeline and wasted time. By validating Helm charts during the build stage, you catch these issues while the developer is still in their workflow.

Integrating OPA into the Pipeline

You can use the conftest utility, which allows you to run your existing Rego policies against your rendered Helm templates. The integration follows this simple flow:

  1. Render: Use helm template to convert your chart into raw Kubernetes YAML.
  2. Scan: Use conftest test to compare the generated YAML against your OPA Rego policies.

Here is an example of what this step looks like in a CI job:

# Render the Helm chart to standard output
helm template my-release ./my-chart > rendered.yaml

# Run OPA policies against the rendered manifests
conftest test rendered.yaml --policy ./policies

If your policy forbids privileged containers, conftest will parse the rendered.yaml, evaluate it against your Rego code, and exit with a non-zero status code if a violation is found. This effectively blocks the deployment pipeline before the helm install or kubectl apply command is ever executed.

Why This Matters

By treating your policies as code in your CI/CD pipeline, you create a "guardrail" experience for developers. They receive immediate feedback in their terminal or CI dashboard rather than waiting for an Admission Controller to block them. This bridge between your OPA policy library and your Helm workflows ensures that your security and compliance standards are enforced consistently across the entire software supply chain.

Key Takeaway: By validating rendered Helm templates against your OPA policies using conftest during CI, you identify non-compliant infrastructure before it is ever deployed, effectively shifting your security enforcement left.