DevOps Policy as Code

Policy as code means writing company rules as files that a program can read and enforce. A rule such as "no storage bucket may be public" moves from a paper document into a small piece of code. The code runs automatically on every change and blocks anything that breaks the rule.

The Building Inspector Example

A city building inspector carries a checklist: exits, fire alarms, wiring. The inspector can visit only so many buildings per day, and mood can affect the decision. Policy as code replaces the human checklist with a tireless inspector. The inspector checks every change in seconds and applies the same rule every time.

Why Teams Use It

  • Rules apply equally to every team.
  • Checks run in seconds, not days.
  • Policies live in Git, so reviews and history work as they do for code.
  • Auditors read the rules and the results directly.

Where Policies Run

 Developer --> Pull request --> [ CI policy check ] --> Merge
                                                          |
                                                          v
 Cloud/Cluster <-- [ Admission policy check ] <-- Deployment
        |
        v
 [ Runtime audit: scan existing resources ]

In the Pipeline

The pipeline scans Terraform plans and Kubernetes files before anything deploys. Failures appear on the pull request.

At Admission

A Kubernetes admission controller sits in front of the cluster API. The controller accepts or rejects each object at creation time.

At Runtime

Audit tools scan existing resources and report ones that drifted from the rules.

Popular Tools

ToolLanguageTypical Use
Open Policy Agent (OPA)RegoGeneral policies for Kubernetes, APIs, and Terraform
GatekeeperRegoOPA inside Kubernetes
KyvernoYAMLKubernetes policies without a new language
HashiCorp SentinelSentinelPolicies for Terraform Enterprise
ConftestRegoTests for any configuration file

Example: A Rego Policy

package kubernetes.admission

deny[msg] {
  input.request.kind.kind == "Pod"
  container := input.request.object.spec.containers[_]
  endswith(container.image, ":latest")
  msg := sprintf("Image %v uses the latest tag", [container.image])
}

The policy rejects any pod whose image uses the latest tag. A pinned version number keeps deployments predictable, and the rule enforces that habit for everyone.

Example: A Kyverno Policy

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-team-label
spec:
  validationFailureAction: Enforce
  rules:
    - name: check-team-label
      match:
        any:
          - resources:
              kinds: [Deployment]
      validate:
        message: "Every deployment needs a team label."
        pattern:
          metadata:
            labels:
              team: "?*"

The policy blocks any Deployment that lacks a team label. Labels like this help with cost reports and incident routing.

Common Policy Ideas

  • Block public storage buckets and open database ports.
  • Require encryption on disks and databases.
  • Limit resources to approved cloud regions.
  • Demand resource limits on every container.
  • Reject containers that run as the root user.
  • Require owner and cost-center tags.

Audit Mode and Enforce Mode

A new policy can break existing workloads. Start in audit mode, where the tool reports violations without blocking anything. Share the report with teams, give them time to fix problems, and switch to enforce mode when the reports are clean.

 Write policy --> Audit mode (report only) --> Teams fix issues --> Enforce mode (block)

Exceptions

Some workloads need a legitimate exception, such as a monitoring agent that must run as root. Record each exception in code with an owner, a reason, and an end date. Review the list regularly and remove old entries.

Testing Policies

Policies deserve tests, like any other code. Write sample inputs that should pass and inputs that should fail, and run them in the pipeline. OPA provides opa test, and Conftest runs checks against files in a repository.

conftest test deployment.yaml --policy ./policies

Compliance Reporting

Standards such as SOC 2, ISO 27001, and PCI DSS ask companies to prove control. Policy results serve as evidence. Reports show which rules ran, which resources passed, and when each failure was fixed.

Key Points

  • Policy as code turns written rules into automatic checks.
  • Checks run in pipelines, at admission, and during audits.
  • Audit mode lets teams adapt before enforcement begins.
  • Tests and recorded exceptions keep policies trustworthy.

Leave a Comment

Your email address will not be published. Required fields are marked *