Skip to main content

Policy as Code: Enforcing Governance

Key Takeaways for AI & Readers
  • Automated Governance: Policy as Code replaces manual reviews with automated rules that enforce best practices and security standards.
  • Admission Control: Policies are enforced at the API level (Admission Controller), blocking non-compliant resources before they reach etcd.
  • Kyverno vs. OPA: Kyverno offers a YAML-native experience for simplicity, while OPA Gatekeeper uses Rego for complex, cross-domain logic.
  • Validation and Mutation: Policy engines can either block invalid requests (Validation) or automatically inject missing fields/defaults (Mutation).

In a large company, you cannot rely on humans to follow "Best Practices" documents. You must enforce rules automatically. This is Policy as Code.

1. Admission Controllers

When you run kubectl apply, the request hits the Admission Controller before it is saved to etcd. This is the perfect place to block bad YAML.

Developer Input

runAsNonRoot:
👮
Kyverno Policy
disallow-root-user

2. Kyverno vs OPA Gatekeeper

Kyverno (K8s Native)

Policies are written in YAML. It's easy to read and manage for Kubernetes engineers.

  • Example rule: "Every Pod must have an owner label."
  • Example rule: "Images must only come from registry.company.com."

OPA Gatekeeper (The Industry Giant)

Policies are written in Rego, a powerful logic language.

  • Pros: Extremely powerful, can handle complex logic that YAML cannot.
  • Cons: Harder to learn (Rego has a steep learning curve).

3. Mutation vs Validation

Policies can do two things:

  1. Validation: Block the request if it's bad. (The "No" button).
  2. Mutation: Automatically "fix" the request.
    • Example: If a developer forgets to set a cost-center label, the policy engine adds a default one automatically.

4. Software Supply Chain Security

Policy engines can also verify Image Signatures (via Cosign). This ensures that only images built by YOUR CI/CD pipeline can run in production, preventing attackers from injecting malicious code.