Uncover hidden risks

Watch how the Wiz platform can expose unseen risks in your cloud environment without drowning your team in alerts.

What is Policy as Code? 

Policy as code (PaC) is the use of code to define, automate, enforce, and manage the policies that govern the operation of cloud-native environments and their resources.

8 minutes read

Defining policies and policy as code

Policy as code (PaC) is the use of code to define, automate, enforce, and manage the policies that govern the operation of cloud-native environments and their resources. 

But before diving further into what policy as code is, let’s take a step back. What are policies? Policies define the rules, criteria, and conditions that stipulate how systems are or must be configured, modified, used, and secured. Policies also describe how systems should behave when all conditions are met. 

Here’s an example: The Kubernetes network policy that controls traffic prevents unwanted ingress to and egress from Kubernetes pods. Before PaC, this policy and hundreds of others would have been documented in plain language. Whenever engineers wrote code or interacted with software, they were expected to know and adhere to an impossible-to-memorize number of policies. And because policies written in plain language can be subject to misinterpretation due to language barriers and contextual nuances, policy violations were quite common, and the code often had to be sent back to the developers for fixes. This constant troubleshooting significantly slowed down time to market (TTM) and took up time that developers could have spent innovating.

With policy as code, policies are written in high-level, human-readable code to make them accessible to all teams—security, operations, development, and administrators.

Benefits of policy as code 

When implemented across the entire stack, PaC streamlines DevOps, DevSecOps, and GitOps implementation, as well as continuous deployment (CI/CD) workflows. Below are other key benefits of PaC.


By codifying policies, stakeholders can ensure that rules mean exactly what they should. PaC’s high-level, readable code format guarantees that policies cannot be misinterpreted. Furthermore, the risk of human errors associated with manual processes is eliminated. Another huge benefit? PaC facilitates policy consistency across the entire stack. For instance, if you’ve implemented network configuration policies, you’ll have peace of mind that they’ll remain consistent across containers, virtual machines, and more. 


Since policies are spelled out as code, queues or review cycles are abstracted and engineers don’t have to keep all the policies in their heads or manually enforce policies every time the need arises. In addition, by versioning policies in Git repositories, engineering teams can keep track of policy modification history and seamlessly go back to a previous version if a newer one turns out to be problematic. That’s why PaC makes for faster and easier software development, testing, and deployment, speeding up TTM and increasing coding velocity.

Infrastructure and network security

If well implemented, PaC can substantially boost your security posture. With PaC, you can effectively prevent employees from using frameworks, container images, and software obtained from untrusted sources. You can also stop certain resource types from being provisioned, deleted, or parked; ensure storage buckets do not have erroneous public write access; sanitize networks by restricting the use of public IPs; and so much more.

Compliance and reporting

Organizations can gather inventory reports on non-compliant systems that include details of a specific policy or policies violated in real time. This facilitates proactive detection of policy adherence issues or drift, which reduces non-compliance incidents. Additionally, PaC tools make compliance audits less painful, providing you with audit trails of who did what and when.

Use cases and implementation for policy as code 

To make the most of PaC’s benefits, use it in any of these scenarios:

  • Admission reviews for Kubernetes: Combining policy-as-code with a Kubernetes admission controller allows you to enforce security policies in your Kubernetes clusters, allowing you to prevent resources from being deployed or modified if they violate the policies you configure centrally. For example, you can:

  • Allow pulling images from specific registries only–Prevent untrusted authors from introducing risks, such as malware or unwanted artifacts, to your images.

  • Deny deploying pods when container images include critical vulnerabilities

  • Zero-trust implementation: More and more enterprises are adopting IAM and RBAC to facilitate zero-trust implementation. But in addition to IAM and RBAC, PaC—with its highly versatile policy logic—can support more complex zero-trust applications by limiting role-based access based on time, location, or duration. PaC can also specify the type of configuration changes that various admins who’ve been granted access can make.

  • Sandboxing: Enterprises can create guardrails—defined as code—that kick in automatically to isolate potentially vulnerable software environments or malicious actions carried out by workloads.

  • Cost savings: PaC is particularly useful for cost control; you can integrate vendor-supplied APIs to calculate runtime costs and use PaC to cap cloud spend/resource usage. Once you’ve implemented cost-saving measures, PaC validates configuration changes (like increased API calls) and resource-deployment operations (including autoscaling) against existing policies before they are allowed to fly, minimizing surprise bills.

How does policy as code work?

In PaC, policies are usually written using purpose-built declarative languages such as Rego and stored in file formats like YAML, JSON, or any language that is compatible with the underlying policy or rule engine. The rule engine contains guardrails that automatically kick in to verify that none of the implemented rules are violated.

When it comes to cloud computing, all policies are created to address three key concerns. Next, let's explore these policy concerns and how they fit into the step-by-step process of PaC implementation.

Core policy concerns

Security, compliance, and operational best practices are the foundational concerns of policy as code. 

Security best practices

Security best practices are guardrails that security teams can use to prevent breaches, spot potential threats or vulnerabilities early, and resolve security incidents effectively. They include practices that reinforce data privacy, network and infrastructure security, access controls, and data retention. Common examples of security policies are those that limit the source of container images to approved registries only and those that prevent compute instances associated with public IPs from being created. 

Compliance requirements

Compliance requirements are data storage, data retention, and client privacy protection standards mandated by regulatory bodies, including GDPR or PCI DSS.  Keeping track of several compliance requirements throughout the software development life cycle can be a showstopper, so enterprises can create corresponding policies and automate their enforcement. 

For example, SOC 2 mandates how enterprises collect, store, and process clients’ PII— as well as who has access to this sensitive data. A relevant policy would restrict sensitive data access on a need-to-use basis using a strategy like role-based access control (RBAC). Or think about the “no compute instance with a public IP” policy we discussed above; this policy would do double duty by both meeting internal security standards and helping you adhere to SOC 2 requirements. 

Operational best practices

Operational best practices ensure your stack runs smoothly. Resource provisioning, scaling, and resource management are just a few operational aspects that teams can tackle with PaC. For instance, policies that encourage engineers to deploy at least two server instances instead of one for redundancy or use medium-sized storage instances to prevent waste and save cost facilitate operational best practices.

Implementing policy as code

Follow these five steps to implement PaC:

1. Define and codify policies

Multidisciplinary teams define the requirements for software installs, system and security configurations, as well as regulatory compliance. Once all policies reflecting the ideal state of the infrastructure are defined, teams proceed to transmute the policies into code using proprietary code tools or open-source tools such as Open Policy Agent (OPA) and Selefra. (We’ll look at these open-source tools later.) 

PaC tools use three inputs to enforce policy compliance: the policy code, which runs the policy compliance checks; data, which is the information that the code verifies machine or engineering teams’ interactions against; and query input, which triggers the policy adherence checks.

2. Automate and test policies

Next, the PaC tool is used to populate the codified policies across the entire stack, including networks, containerization environments, storage instances, CI/CD pipelines, and testing environments. The tool also automates policy code execution and helps to test the policies to prevent policy drift and ensure that all codified policies mean exactly what you intended.

3. Write and upload app code

With PaC in place, DevSecOps teams can proceed to write code and interact with cloud and network infrastructure (e.g., by provisioning cloud resources or applying firewall rules) while adhering to the policies.

4. Automatically scan for violations

At scheduled intervals, or whenever code is executed and/or resources are provisioned, the PaC tool automatically scans for violations by evaluating the query input against the policy code and data. Once the scan is done, it outputs a query result in JSON stating its conclusion: Has there been a violation or not? 

5. Roll out software

If a violation is found, it is flagged with recommendations for its correction. Engineering teams then resolve any violations and roll out the software, updates, or configuration changes.

PaC vs. IaC vs. SaC

Policy as code (PaC), infrastructure as code (IaC) and security as code (SaC) are all codified rules governing IT operations. However, IaC leverages PaC rules when provisioning infrastructure, while SaC is an aspect of PaC that can be used to manage infrastructure as code. Below is a bird's eye comparison of the three concepts.

DefinitionA set of rules and criteria for your IT environment that’s written as codeThe code used to build and manage infrastructure in adherence to PaC rulesA set of codified security protocols used to integrate security measures into the software development process
FocusKeeping security operations, compliance management, infrastructure provisioning, and data management in line with regulatory and organizational policiesAutomating infrastructure provisioningShifting security left
Use case examplesAdmission reviews for Kubernetes, zero-trust implementations, cost savings, sandboxingProvisioning production, sandboxing, testing and deployment environments, and CI/CD pipelinesAccess controls, sandboxing, security testing, and vulnerability scanning

Open-source PaC tools

There are several open-source policy engines enterprises can leverage for PaC implementation. Below are the top choices. 

Open Policy Agent

Open Policy Agent (OPA) is a Cloud Native Computing Foundation (CNCF) Graduated project designed to provide a consistent framework for implementing policy as code. OPA can enforce policies across microservices, CI/CD pipelines, Kubernetes, servers, API gateways, and more. OPA policies are expressed in a high-level declarative language called Rego.

HashiCorp Sentinel 

HashiCorp Sentinel is a policy-as-code framework that allows organizations to define, enforce, and manage policies across their infrastructure. Integrated with HashiCorp's suite of tools like Terraform, Vault, and Consul, Sentinel enables automated, fine-grained governance by ensuring compliance and security policies are consistently applied throughout the infrastructure lifecycle.


Selefra, short for “select from infrastructure,” integrates with multi-cloud and SaaS environments, including Kubernetes, GitHub, AWS, Azure, GCP, and Slack to provide policy suggestions and help implement security, architecture, and cost-related policies.

Kyverno OSS

Kyverno OSS is the open-source version of Kyverno. It is a CNCF project used to enforce security and governance policies in Kubernetes environments, with policies codified as Kubernetes resources.


Kubewarden is a Kubernetes policy engine for enforcing security and compliance in K8s environments, including clusters and containers. You can create Kubewarden policies using DSLs or regular programming languages and then leverage container registries to deliver them as WebAssembly modules.

The downsides of open-source tools

Though the open-source PaC tools we’ve examined can be beneficial, they rarely offer the flexibility, features, and coverage of proprietary tools. Some are built only for specific parts of your IT stack (for example, Kubewarden for Kubernetes), and some require steep learning curves (like Chef, which uses Ruby code exclusively and does not offer flexible frameworks and conventions).

PaC with Wiz

Policy as code can help businesses achieve their governance goals more efficiently, speed up time to market, and keep cloud spend in check. But to effectively implement PaC, enterprises must carefully select the right tool for the job. The tool should be easy to use, and it must help define policies clearly, codify them thoroughly, test rigorously, and monitor your entire stack for policy adherence. 

This is where Wiz shines. Wiz provides you with thousands of built-in policies that you can also extend to suit your unique use cases using the Rego declarative language. Our easy-to-use interface facilitates multidisciplinary team collaboration and allows you to enjoy seamless version control. With Wiz, you can implement policy as code at a virtually unlimited scale and keep comprehensive audit trails for stress-free compliance checks. Secure and ensure compliance across your entire stack with context-sensitive and enterprise-controlled policies today. Request a demo to get started.

Secure Your Cloud from Source to Production

Learn why Wiz is one of the few cloud security platforms that security and devops teams both love.

Get a demo

Continue reading

What are CIS benchmarks?

Wiz Experts Team

CIS benchmarks are publicly available security roadmaps offering core recommendations to guide organizations on hardening their IT systems against cyber threats.

GitOps vs. DevOps

While DevOps delineates collaboration and automation practices that emphasize infrastructure provisioning and continuous monitoring, GitOps extends its concepts by employing Git as the single source of truth for both application and infrastructure settings.

Kubernetes Namespaces: Security Best Practices

Kubernetes namespaces divide a given cluster into virtual clusters, helping to separate and manage resources while still keeping them within the same physical cluster. By segregating workloads and applying policies per namespace, you can create boundaries that keep your multi-tenant environments safe and organized.

Linux containers: A security review

Understanding the nuances of Linux containers is crucial for building robust, secure applications. This blog post provides insights into the practical implementation of containers, focusing on both their strengths and potential pitfalls.