Policy as Code: Benefits, Examples, and How to Get Started

What is policy as code, and why does it matter for modern infrastructure?

Policy as code (PaC) defines and enforces organizational rules through code that teams version, test, and review as part of software development. Modern cloud-native environments evolve quickly, increasing the risk of misconfigurations, policy drift, and deployment failures. Codifying expectations removes ambiguity, reduces manual effort, and provides engineering and security teams with a consistent way to govern cloud resources.

Without automated guardrails, teams rely on manual oversight, which creates real gaps. Wiz Research found that 61% of organizations expose secrets in public repositories. GitHub accounts for 81% of total enterprise repositories, and more than 30% of those repos are public, making the platform a prime target for threat actors. A developer might inadvertently commit an AWS access key to a public repo. Without PaC to block that commit, a malicious actor can scrape the key, deploy instances for cryptomining, or extract sensitive data. PaC closes that gap at the source.

Secure Coding Best Practices [Cheat Sheet]

Your comprehensive, go-to resource for embedding security into every stage of your code development.

What are the benefits of policy as code?

PaC creates a unified approach to defining and enforcing organizational requirements across modern cloud-native environments. For example, when teams adopt PaC across the stack, they gain accuracy, efficiency, stronger security outcomes, and more predictable deployments. These benefits materialize because PaC replaces manual interpretation with automated checks that operate consistently across infrastructure, CI/CD pipelines, and operational workflows.

Below are the core benefits of PaC:

  • Clarity and consistency improve when codified policies carry a single, authoritative meaning across containers, virtual machines, and cloud services, eliminating the confusion inherent in written documentation.

  • Fewer deployment rollbacks result from automated policy checks that catch issues earlier in the workflow rather than at late-stage security reviews.

  • Teams move faster without manual approvals or lengthy review queues. Git stores every policy change, supporting peer review and safe rollbacks when needed.

  • Proactive enforcement reduces misconfigurations across Kubernetes, AWS, Azure, and other cloud platforms by blocking untrusted container images, public storage buckets, and workloads with unnecessary network exposure.

  • Continuous compliance stays audit-ready because every policy change creates a timestamped, versioned record, giving security and compliance teams a clear trail to demonstrate control adherence during audits or regulatory reviews.

How does policy as code work?

PaC expresses organizational rules in executable formats that policy engines evaluate during development, provisioning, and deployment. These engines also analyze resource configurations and application behavior to determine whether changes follow defined policies. Policy as code functions effectively because policies use declarative, human-readable formats, integrate with version control alongside code, and leverage CI/CD pipelines and runtime checks for automatic enforcement. Continuous evaluation ensures every change is consistent.

The following principles illustrate how PaC functions across modern cloud systems:

  • Policies use human-readable declarative languages like Rego and YAML, empowering teams to define expectations with clear, testable, versioned logic.

  • Policy engines, including Open Policy Agent (OPA) and HashiCorp Sentinel, evaluate resources by comparing real-time inputs against defined policy logic to verify that changes meet security, compliance, and operational requirements.

  • CI/CD systems integrate these checks so pipelines validate infrastructure as code (IaC), application code, and configuration changes before deployment.

  • Runtime environments enforce the same rules to prevent drift and maintain workload compliance as developers iterate on features and infrastructure.

To illustrate how PaC works, the following examples demonstrate common policy patterns:

Rego policy 

OPA evaluates the Rego policy below via Conftest during CI. Conftest passes a Terraform plan file as input to the policy, allowing OPA to inspect proposed resource changes before they’re applied.

Codifying this logic prevents any Terraform plan that attempts to configure an S3 bucket ACL as public from reaching deployment.

package terraform.s3
deny[msg] {
  resource := input.resource_changes[_]
  resource.type == "aws_s3_bucket_acl"
  acl := resource.change.after.acl
  acl == "public-read" or acl == "public-read-write"
  msg = sprintf("S3 bucket %v has an overly permissive ACL (%v).", [resource.address, acl])
}

Kyverno policy 

The Kyverno policy below operates as an admission controller within the Kubernetes API server. It evaluates pod specifications during creation or update and rejects any pod that attempts to run a privileged container.

In this example, the policy enforces least privilege by blocking workloads that set securityContext.privileged to true before they enter the cluster.

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: disallow-privileged
spec:
  validationFailureAction: enforce
  rules:
    - name: block-privileged-containers
      match:
        resources:
          kinds:
            - Pod
      validate:
        message: "Privileged containers are not allowed."
        pattern:
          spec:
            containers:
              - =(securityContext.privileged): "false"

Both examples show how teams set expectations in code for policy engines to enforce across cloud resources, Kubernetes clusters, and IaC templates. When the engine detects a violation, it returns structured feedback that CI/CD systems or developers can use to remediate issues before deployment.

PaC works effectively because it applies the same rules consistently during development, provisioning, and runtime. Codifying these rules reduces manual oversight, prevents misconfigurations from slipping into production, and preserves a clear audit trail of policy evolution.

DevOps Security Best Practices [Cheat Sheet]

Designed for DevOps and platform engineers, AppSec teams, and cloud architects.

How to get started with policy as code: A step-by-step implementation guide

A successful PaC program begins with clear policy requirements, consistent policy language, and automated checks integrated across development and deployment workflows. Teams gain the most value when they treat PaC as a shared responsibility across security, DevOps, and development, evolving their policies as cloud environments grow.

The following three steps outline a practical roadmap for implementing PaC:

1. Define policy requirements and select a policy language

Teams must identify their security, compliance, and operational requirements before codifying rules. These standards must reflect regulatory obligations, organizational benchmarks, and common misconfigurations observed within existing environments. 

Once teams outline relevant policies, they must choose a policy language that fits their ecosystem. Rego, YAML, and Sentinel provide flexibility by offering readable syntax and integrating with popular cloud security and DevOps tooling. Version control systems like Git track policy changes and enable collaboration on rules that evolve with infrastructure and application needs.

2. Integrate policy as code into CI/CD pipelines

PaC delivers meaningful outcomes when teams embed checks directly into continuous integration and continuous deployment pipelines. Pipeline integration ensures that infrastructure as code, application changes, and configuration updates pass defined policies before reaching production. CI systems evaluate policy logic using engines such as OPA or HashiCorp Sentinel and return structured results with actionable guidance. 

Automated checks reduce rework, accelerate reviews, and help developers correct misconfigurations early in the development lifecycle, when fixing changes costs less.

3. Monitor, test, and evolve policies over time

A mature PaC program requires ongoing validation as cloud environments grow and engineering teams adopt new technologies. Continuous monitoring identifies policy drift, emerging misconfigurations, and unintended coverage gaps. Regular testing ensures that policies behave as intended and don’t block valid changes. 

Over time, organizations refine rules based on real-world findings, expand coverage to new environments, and incorporate context-aware insights to improve accuracy. The continuous improvement loop strengthens governance and supports application delivery without slowing innovation.

Policy as code best practices and real-world examples

Teams unlock the full value of policy as code by applying structured best practices and proven implementation patterns across cloud environments. Applying these practices prevents common pitfalls, strengthens governance, and simplifies policy adoption for developers and operators.

The following best practices provide practical guidance for teams that want to build reliable, scalable PaC programs:

  • Write policies that express clear and testable intent to help engineering teams understand expected behavior and remove guesswork.

  • Keep policy scope targeted to avoid disruptive false positives and ensure that policies support development velocity without stalling delivery.

  • Reuse shared policy libraries across teams and repositories to maintain consistent enforcement in multi-cloud and multi-account environments.

  • Store all policies in version control so teams can review, test, and track policy evolution as infrastructure scales.

  • Combine static analysis with runtime checks to prevent misconfigurations before deployment and detect drift as systems evolve.

Here are some practical examples that demonstrate how these best practices operate:

Kubernetes admission control

Organizations validate workloads before execution using PaC with admission controllers. Admission control helps teams block untrusted container images, prevent workloads from requesting insecure privileges, and enforce configuration standards across clusters.

The following example demonstrates how an admission controller enforces image trust by denying pods that reference container images from unapproved registries.

package k8s.admission

deny[msg] {
  input.request.kind.kind == "Pod"
  container := input.request.object.spec.containers[_]
  not startswith(container.image, "registry.example.com")
  msg = sprintf("Container image %q must come from an approved registry.", [container.image])
}

Zero trust implementations

PaC strengthens zero trust architectures by controlling access based on time, location, identity attributes, or workload context. Codifying zero trust policies reduces the risk of role sprawl and makes IAM governance more predictable across AWS, Azure, and Kubernetes workloads.

Example scenarios include enforcing time-bound access for administrative roles, restricting sensitive actions to workloads with approved identities, or requiring contextual signals, such as source network or environment, before granting IAM permissions.

Sandboxing and workload isolation

Teams define automatic guardrails that isolate suspicious workloads or configuration changes. When infrastructure behavior deviates from an approved baseline, policy engines trigger controls that route workloads into isolated environments for deeper investigation. For example, a workload that suddenly exposes a public network port or pulls an image from an untrusted registry can automatically quarantine within a restricted namespace with no external access.

Cost governance

Cloud spend often increases when resource configurations drift from intended baselines. PaC helps teams control costs by validating autoscaling settings, API usage patterns, and resource sizing before provisioning. Policy controls prevent unexpected billing spikes and support predictable cloud planning.

Common cost-governance scenarios enforced through PaC include:

  • Restricting autoscaling limits to prevent services from scaling beyond approved instance counts or thresholds during traffic spikes

  • Blocking oversized resources, such as high-memory compute instances or premium database tiers, outside approved environments

  • Enforcing API usage quotas for serverless and managed services to avoid runaway consumption

  • Detecting post-deployment drift where resized or reconfigured resources bypass previous approvals and increase costs

Effective PaC programs evolve with the environment and treat policies as active components of cloud governance. Teams that adopt iterative improvement, shared ownership, and strong validation workflows reduce risk while maintaining development speed.

PaC vs. IaC vs. SaC

PaC, IaC, and security as code (SaC) serve unique roles in modern software development and cloud governance. While these practices frequently intersect, they solve distinct problems. Differentiating between these disciplines clarifies how each supports secure and reliable infrastructure provisioning.

The following core differences distinguish the three:

ParametersPaCIaCSaC
What it doesDefines and enforces organizational rules for security, compliance, and operationsManages and provisions infrastructure through code templatesEmbeds security controls directly into development workflows
Primary focusGoverns system behavior across infrastructure, workloads, and appsDescribes and deploys the desired state of cloud resourcesSecures the software development lifecycle end-to-end
Common tools and usageOPA and Kubernetes for admission reviews, Sentinel for cost governanceTerraform for VPC provisioning, CloudFormation for storage deploymentAccess control logic, vulnerability scanning rules, secure configuration patterns
How they connectValidates that IaC templates meet policy requirements before deploymentUses PaC to stay compliant at deploymentUses PaC to enforce consistent rule sets across infrastructure and apps

Open-source PaC tools

Open-source policy engines give teams flexible, extensible ways to enforce PaC across cloud workloads, IaC templates, and Kubernetes environments. Tooling maturity, learning curves, and integration depth vary significantly, requiring teams to understand where each performs best.

The following tools represent the most widely adopted options for PaC implementation:

OPA

Open Policy Agent provides a unified framework for enforcing policies across microservices, CI/CD pipelines, Kubernetes clusters, servers, and APIs. Teams write policies in Rego, an expressive language suited for complex cloud environments. OPA seamlessly integrates with Kubernetes admission control workflows, enables granular decisions, and scales across multi-cloud environments. While the learning curve requires investment, the long-term value remains high for teams that want a single engine across their stack.

HashiCorp Sentinel

HashiCorp Sentinel aligns closely with Terraform, Vault, Consul, and other HashiCorp tools, making it a strong choice for organizations seeking tight control over IaC provisioning workflows. Sentinel enforces rules before resource deployment and prevents drift at the infrastructure layer. Its purpose-built language delivers power but requires training for teams unfamiliar with the HashiCorp ecosystem.

Selefra

Selefra evaluates policies across multi-cloud and SaaS environments, including AWS, Azure, Google Cloud, Kubernetes, GitHub, and Slack. The tool prioritizes inventory analysis and configuration insights, helping teams uncover misconfigurations and architectural inconsistencies. Its SQL-based syntax offers a shallower learning curve for teams that prefer a query-driven approach to policy evaluation.

Kyverno OSS

Kyverno OSS treats policies as Kubernetes resources, which simplifies adoption for platform teams already familiar with YAML and cluster-native workflows. The tool excels at validation and mutation tasks within Kubernetes environments, including enforcing pod security standards, controlling image sources, and maintaining configuration baselines. Its Kubernetes specificity lowers adoption friction but limits scope to cluster-focused use cases.

Kubewarden

Kubewarden enforces rules in Kubernetes by compiling policies into WebAssembly modules written in DSLs or common programming languages such as Python, Rust, or Go. This approach gives teams language flexibility and strong isolation for policy execution. Kubewarden effectively serves organizations that want to reduce the overhead of learning a dedicated policy language while maintaining high performance.

How Wiz strengthens your policy as code implementation

Wiz strengthens PaC programs by integrating policy enforcement, risk prioritization, and developer-ready, shift-left guardrails across the entire software development lifecycle. Many teams struggle with fragmented visibility, unclear ownership, and inconsistent enforcement when relying solely on open-source policy engines. Wiz resolves these challenges by providing a unified view of infrastructure, application code, and cloud resources, paired with automated checks that span development through runtime.

The following capabilities demonstrate how our platform enhances PaC adoption at scale through its AI-powered capabilities:

  • Wiz Code enforces security policies throughout CI/CD pipelines, enabling teams to validate IaC templates, container images, and configuration changes before they reach production.

  • Context-aware analysis prioritizes violations that pose real risk, allowing engineering teams to focus on meaningful fixes instead of clearing long lists of low-impact alerts.

  • Custom policy support allows teams to author rules that align with internal standards, regulatory obligations, and cloud governance requirements without disrupting developer workflows.

  • Seamless integration with developer tooling delivers immediate feedback when code or configuration violates organizational policies, accelerating remediation and reducing operational friction.

  • Continuous monitoring across workloads, cloud resources, and applications verifies that deployed systems remain aligned with security policies and reduces drift across multi-cloud environments.

Wiz improves PaC outcomes by embedding checks directly into daily engineering workflows, supporting shift-left adoption, and providing stakeholders with consistent visibility across the stack. With these capabilities in place, teams can enforce meaningful guardrails to maintain security without slowing development speed or sacrificing cloud agility.

Improve your security today by downloading our Secure Coding Best Practices [Cheat Sheet]. Transform your policy as code guidelines into concrete coding patterns that developers can apply in every pull request.


FAQ about policy as code

Below you’ll find answers to common questions about policy as code: