Policy as code turns cloud governance from a document people must remember into checks that can be tested, reviewed, and enforced. This guide provides a reusable checklist for combining Open Policy Agent (OPA), Kyverno, CI checks, and Kubernetes admission controls without blocking delivery unnecessarily.
Overview
Policy as code expresses security, compliance, and operational rules in machine-readable form. A policy might require every workload to identify an owner, prevent privileged containers, restrict images to approved registries, or ensure that production resources include cost-allocation metadata. Automated controls can evaluate configuration before deployment, during a pull request, or when a workload reaches a Kubernetes cluster.
OPA and Kyverno solve related problems but use different approaches. OPA is a general-purpose policy engine. Its Rego language can evaluate structured data such as Kubernetes manifests, Terraform plans, API requests, and application-specific documents. OPA is often used through integrations such as Gatekeeper in Kubernetes or through direct API calls from a delivery system.
Kyverno is designed around Kubernetes resources and uses policy rules that resemble familiar YAML patterns. It can validate resources, mutate them, generate related resources, and report policy results through Kubernetes-oriented workflows. The choice between OPA and Kyverno should follow the systems you need to govern, the languages your team can maintain, and the enforcement points you require. They can also coexist when a platform has both Kubernetes-specific and broader policy needs.
A reliable policy program separates four activities: defining a rule, testing it against representative inputs, deciding where it should run, and managing exceptions. Treating admission control as the entire solution is risky. A rule that only runs when Kubernetes accepts a resource may be too late for developer feedback, while a rule that runs only in CI may not protect against direct cluster changes.
Start with a small set of high-confidence controls. Good first candidates are policies with clear ownership, a low rate of legitimate exceptions, and a direct connection to security or reliability. Examples include requiring resource requests and limits, rejecting host-level access unless explicitly approved, requiring an image registry, and checking that workloads have an owner or service identifier.
Checklist by scenario
1. Establishing a policy baseline
- Identify the asset and risk: Write down what the rule protects, such as cluster integrity, data access, workload reliability, or cost visibility.
- Define the scope: Specify environments, namespaces, resource kinds, teams, and stages where the policy applies.
- Describe the desired state: Use an objective test. “Production deployments must use an approved registry” is more actionable than “production images must be safe.”
- Name the owner: Assign a team responsible for reviewing the rule, responding to violations, and approving changes.
- Record the exception path: Define who can approve an exception, how long it lasts, and what evidence is required.
- Choose the enforcement mode: Begin with audit or warning mode when the current state is unknown; move to rejection only after violations have been reviewed.
2. Adding Kubernetes admission controls
- List the resource types the rule evaluates. Avoid applying a workload policy indiscriminately to unrelated objects.
- Decide whether the policy validates, mutates, or generates resources. Validation is usually the easiest behavior to reason about. Mutation can improve consistency but should be visible to developers.
- Exclude system namespaces and control-plane components only when there is a documented reason. Broad exclusions can create an unmonitored path.
- Test create, update, and delete behavior where relevant. A policy that protects initial creation may not cover later changes.
- Check failure behavior. Determine whether an unavailable policy engine should fail closed, fail open, or trigger an operational alert based on the risk and availability requirements.
- Return an actionable message that identifies the resource, the failed condition, and the expected correction.
Admission policies should be part of a wider Kubernetes security program. Use the Kubernetes security checklist to review identity, network, workload, and cluster-hardening controls that policy rules alone cannot replace.
3. Integrating policy into CI/CD
- Run policies against rendered manifests rather than only the source templates. Rendering exposes the values that will actually reach the cluster.
- For infrastructure changes, evaluate the planned representation where possible, while recognizing that a plan may not reveal every runtime property.
- Make policy checks visible in pull requests. Developers should see the failed resource and the correction before a deployment attempt.
- Pin policy bundles, rule versions, or action dependencies according to your change-management practice, then update them deliberately.
- Separate blocking checks from advisory checks. A single experimental rule should not make the entire pipeline difficult to interpret.
- Store policy tests with the policy code and require review for changes to both rules and exceptions.
A GitHub Actions workflow can run manifest rendering, policy evaluation, tests, and security checks as separate steps. This makes failures easier to diagnose than one opaque governance stage. For workflow organization ideas, see the CI/CD pipeline templates guide.
4. Governing infrastructure and cloud configuration
- Choose controls that can be evaluated consistently from configuration or plan data.
- Check public exposure, encryption settings, identity permissions, region constraints, and required ownership metadata according to your environment.
- Distinguish a missing value from an invalid value. Both should produce useful feedback, but remediation may differ.
- Connect policy results to the change owner and environment so violations do not become anonymous queue items.
- Review whether a rule duplicates a stronger control provided by the cloud platform or Terraform workflow.
Keep governance connected to infrastructure ownership and lifecycle management. A consistent Terraform project structure makes it easier to locate policy inputs, environment differences, and the team responsible for remediation; the Terraform project structure guide provides a related organizational checklist.
5. Managing exceptions
- Require a reason, owner, approval, affected resource, and expiration date.
- Use the narrowest possible scope. Prefer one workload or namespace over an entire cluster.
- Make exceptions discoverable through labels, annotations, a repository file, or another auditable record.
- Alert before expiration and remove exceptions that are no longer needed.
- Review repeated exceptions as evidence that the policy may be too broad, poorly documented, or missing a supported operating pattern.
What to double-check
Policy semantics: Confirm that the rule evaluates the field you intended, including nested fields, lists, inherited values, and defaulted settings. A syntactically valid policy can still enforce the wrong condition.
Input differences: Test the representations seen at each enforcement point. A source manifest, rendered manifest, admission request, and cloud plan may contain different fields or structures.
Scope and exclusions: Review namespaces, labels, resource kinds, service accounts, and environment selectors. A policy that is too broad creates noise; one that is too narrow creates false confidence.
Mutation effects: If Kyverno or another mechanism changes a resource, verify the resulting object and confirm that developers can see what changed. Mutations should not hide an important security decision.
Performance and availability: Check evaluation time, policy-engine health, webhook behavior, and the effect of a control-plane or dependency outage. Governance is part of the delivery path and needs an operational owner.
Message quality: Ask a developer who did not write the policy to fix a deliberately invalid example. If the message does not identify the failed rule and a realistic correction, improve it before enforcing the policy.
Coverage: Track which environments and resource types are evaluated, how many violations are open, how long remediation takes, and how many exceptions are active. Coverage is more useful than simply counting the number of policies.
Related controls: Policy as code does not replace least-privilege IAM, image scanning, secrets management, network controls, runtime monitoring, or incident response. Align it with your broader Kubernetes security checklist and observability practices.
Common mistakes
- Enforcing everything immediately: Starting in blocking mode can interrupt legitimate workloads before the team understands the baseline. Begin with measured audit results for ambiguous rules.
- Writing vague policies: Rules such as “use secure images” are difficult to test and explain. Define an observable property, such as an approved registry or required digest strategy, when that matches your risk model.
- Ignoring generated configuration: Templates and overlays can hide the final values. Evaluate rendered output and include representative environment variations in tests.
- Creating permanent bypasses: An exception without an owner or expiry becomes an alternate policy. Make temporary access visible and reviewable.
- Duplicating rules across tools: The same control in several engines can produce inconsistent results and conflicting messages. Assign one authoritative implementation or document why multiple checks are necessary.
- Testing only compliant examples: Include valid, invalid, boundary, and exception cases. Test updates as well as creates, and include system-managed resources when they fall within scope.
- Measuring policy count instead of outcomes: More rules do not necessarily mean better governance. Review prevented risks, remediation time, false positives, exception trends, and coverage.
When to revisit
Review policy as code whenever workflows, tools, or risk assumptions change. A practical review cycle includes the following checkpoints:
- Before a seasonal planning cycle: Reconfirm ownership, priority risks, exception inventory, enforcement modes, and the resources expected to be added or retired.
- Before adopting a new platform or cluster: Verify that selectors, namespaces, admission configuration, CI integration, and reporting cover the new environment.
- When deployment workflows change: Re-test rendered manifests, branch protections, reusable workflows, policy bundles, and rollback procedures.
- After a security or reliability incident: Determine whether a preventive rule, detection rule, or clearer exception process would reduce recurrence. Document the lesson without assuming every incident should become a blocking policy.
- When a tool or policy engine changes: Recheck supported syntax, integrations, evaluation behavior, failure handling, and migration requirements in a non-production environment before rollout.
- After repeated violations: Decide whether the rule needs better developer guidance, an automated fix, narrower scope, or a different enforcement point.
For an actionable maintenance routine, schedule a recurring policy review and bring together platform engineering, security, service owners, and incident responders. Compare policy results with deployment failures, operational alerts, and postmortems rather than reviewing governance in isolation. The SRE incident response template can help connect policy-related failures to ownership, communication, and follow-up work.
Before your next production change, use this short sequence: choose one risk, identify the input and enforcement point, write a testable rule, test compliant and noncompliant examples, run it in audit mode, review exceptions, then enforce it with a clear rollback path. That process keeps cloud governance practical while giving teams a repeatable way to improve security and reliability as their systems evolve.