Infrastructure as Code | 3 Min Read

What is Policy-as-Code and Why do you Need it?

Let us start with what a policy is before we describe Policy as Code. A policy consists of a rule or plan related to and associates with particular situations. It contains a comprehensive plan that embraces acceptable procedures used as a rule or process.

The policy is a way to enforce conditions and rules that prevent unauthorized access to resources such as databases, services, storage, or the environment. For multiple areas of your operating environment, policies could be created. You can achieve stability and security in your environment; you can monitor who has access to what.

Types of Policies

  • Compliance Policies: Ensure compliance standards like PCI-DSS, SOC, or GDPR.
  • Security Policies: Internal Security Policies for security and infrastructure principles and data.
  • Operational Excellence: Policies for service interruption or degradation.

    What is Policy as Code?

Policy as Code is the writing code plan as a high-level language to manage and automate the policies. Similar to the concept of Infrastructure-as-Code (IaC), Policy-as-Code (PaC) is the concept of codification of your policies.

For implementing the policies created by high-level language, you need first to have a policy engine that will take the policy, query, and desired data as input and give out the query result based upon the policy attached/issued. Some of the policy engines available are Open Policy Agent and Hashicorp's Sentinel.

Policy as Code helps maintain a standard within your organization by enforcing certain rules across the organization or within specific clusters. Having codified policies improves the automation and efficiency in tasks by enforcing the rules that prevent wrong setup and configuration in your cluster/environment.

Policies you want to enforce could contain guidelines or agreed-upon conventions and best practices that need to be followed.


OPA (Open Policy Agent)

package terraform
import input as tfplan
threshold = 15
weights = {
    "aws_autoscaling_group": {"create": 8}
resource_types = {"aws_autoscaling_group”}
default auth = false
auth {
    score < threshold
score = s {
    all := [ x |
            some resource_type
            crud := weights[resource_type];
            cre := crud["create"] * n_create[resource_type];
            x := cre
    s := sum(all)

#List Available Resources
resources[resource_type] = all {
    some resource_type
    all := [name |
        name:= tfplan.resource_changes[_]
        name.type == resource_type

Terraform Sentinel

import "tfplan-functions" as plan

import "aws-functions" as aws

param mandatory_tags default ["Name", "ttl", "owner", "se-region", "purpose", "terraform"]

allAWSResourcesWithStandardTags = aws.find_resources_with_standard_tags()
violatingAWSResources = plan.filter_attribute_not_contains_list(allAWSResourcesWithStandardTags, "tags", mandatory_tags, true)

# Main rule
main = rule {
  length(violatingAWSResources["messages"]) is 0

Why policy as Code?

The motive behind policy as Code is the same as the idea behind Infrastructure as Code, which revolves around writing the codified state's policies/configurations. Cost savings, enhanced compliance, effective implementations, fine-grained infrastructure control, and better use of native tools from cloud providers can be achieved through proper policies.

For example, suppose service is assigned using any policy. In that case, you can run a series of tests against it to make sure it meets your rules/procedure standards rather than manually testing and verifying each service.


Governance and Compliance

Policy as Code helps you understand the associated compliance and governance checks/routine with which your service needs to comply. 


Having policy as Code, all the operations, rules, procedures to comply on, and logic are stated and written in Code, with which proper documentation and comments can be easily understood by anyone rather than making them understand verbally.

Version Controlled

As policies are being used as Code, so we have the power to store and integrate them on some version control system, which will keep a check on all desired processes like pull requests, history, and many more. 

Integration with Automation

As Policies are used and stored as a text file, there is an upper hand in using them with automation tools. For example, you can integrate a policy for your infrastructure setup configuration, which will enforce some rules before setting up the actual infrastructure.

Best Practices

Policy as Code enables you to deploy best practices as policies. You can also package solutions based on the operational criteria in packages or regulation sets. This provides the tools you deploy with repeatable and fine-grained power. Rule Packs can be deployed as Policy classes or rules on individual resource stacks or several stacks.

Some Use Cases

Access Control

Having a policy containing the rules about the authorization for any service can be very useful. Here we can take the example of OPA(open policy agent) that integrates policy enforcement across a stack and allows you to specify policy as code and easy APIs to load policy decisions from your software. 

OPA(Open policy agent) can be used to enforce policies on microservices, Kubernetes pipelines, CI / CD pipelines, and more. Rego, a declarative language, is being used for querying the data.


We can manage Kubernetes clusters with policies. The policies will contain rules for the variety of kubernetes objects like pods, namespace, deployments, nodes, and many more. For example, we can enforce docker images being used to be fetched from the trusted source that will be used in the pods and deployments.

Infrastructure Provisioning

Attachment of infrastructure policies with resources like databases and services to limit unauthorized access or even enforce cost optimization policies related to infrastructure. You can define rules and regulations regarding the access that needs to be met before actually using the services/storage.


Policy as Code attempts to reduce overhead and documentation. It would help if you still had well-documented rules to specify how accepted, and controlled changes are and checklists for processes that can not be automated. 

However, most protocols and acceptance gates are applied by automatic rules and requirements, depending on the automated pipeline and software to ensure that all steps are taken. In terms of repeatability, versioning, and checking, we also speak about Policy as Code, which directly supports developers and operators.

Policy as Code uses codified and automatic compliance policies. This approach applies to infrastructure as Code, offering related advantages. Avoiding a ticketing workflow allows organizations to provide more end-to-end integration and self-service capabilities, minimizing developers' and operators' problems.


Fresh news directly to your mailbox