Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Compliance and Governance

Policy as Code

Learn policy as code: express security rules as testable code, enforce them in pipelines and clusters, and understand OPA/Rego, Kyverno and cloud guardrails with runnable examples.

A written security policy such as "all storage must be encrypted and private" is useful for people, but a computer cannot enforce a PDF. Policy as code means writing such rules in a machine-readable form so that software can check them automatically, every time, in the place where the change happens: in a pull request, in a deployment pipeline or at the moment a resource is created.

The benefits are the same as for any code. Rules are versioned, reviewed, tested and applied consistently, instead of living in somebody's head. In this lesson you will see the main tools, the three places to enforce policy, and you will build a miniature policy engine in Python to understand how real ones work.

Where policy runs

flowchart LR
    A["Developer writes IaC or manifests"] --> B["Pull request check<br/>(shift left)"]
    B --> C["Pipeline gate<br/>before deploy"]
    C --> D["Admission control<br/>at the API"]
    D --> E["Running cloud"]
    E --> F["Continuous audit<br/>detect drift"]

Check early for fast feedback, at the API as a safety net and continuously to catch manual changes.

Stage Example Result of a violation
Pull request / CI Scan Terraform or Kubernetes files with a policy engine Build fails with an explanation
Admission Kubernetes admission controller, cloud service control policy The API refuses the request
Audit / detective Scan live resources on a schedule Finding or ticket, optionally auto-remediation

Common tools

  • Open Policy Agent (OPA) is a general-purpose engine. Policies are written in Rego, a declarative query language. Conftest applies OPA policies to configuration files, and Gatekeeper enforces them inside Kubernetes.
  • Kyverno is Kubernetes-native: policies are YAML resources, with validate, mutate and generate rules.
  • HashiCorp Sentinel and Terraform Cloud policies enforce rules on Terraform plans.
  • Cloud-native guardrails: AWS Service Control Policies and Config rules, Azure Policy, Google Cloud Organization Policy. These can forbid actions across a whole organisation, for example "no public IP addresses" or "only these regions".
  • Checkov, tfsec/Trivy and KICS ship with hundreds of built-in rules for infrastructure as code; see infrastructure as code scanning.

A Rego policy (read-only)

This example denies any storage bucket that is public or unencrypted. The input is a resource description as JSON. It is shown for reading; the runnable exercise below recreates the same logic in Python.

REGO
package storage

deny[msg] {
  input.type == "storage_bucket"
  input.public_access == true
  msg := sprintf("bucket %v must not be public", [input.name])
}

deny[msg] {
  input.type == "storage_bucket"
  not input.encryption.enabled
  msg := sprintf("bucket %v must be encrypted", [input.name])
}

A Kyverno policy (read-only)

YAML
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: disallow-latest-tag
spec:
  validationFailureAction: Enforce
  rules:
    - name: require-pinned-image
      match:
        any:
          - resources:
              kinds: ["Pod"]
      validate:
        message: "Images must not use the :latest tag."
        pattern:
          spec:
            containers:
              - image: "!*:latest"

Build a miniature policy engine

A policy engine has three parts: policies (rules that return a message when violated), inputs (resource descriptions) and a runner that applies all policies to all resources and reports the results. The Python version below mirrors that design.

Python A tiny policy engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The engine reports four violations. In a pipeline the same runner would end with a non-zero exit code, and the pull request could not be merged until the resources were fixed.

Testing your policies

Policies are code, so they need tests: a bad resource must be rejected, a good one must pass, and an edge case must behave as intended. Without tests, a rule can silently stop matching after a schema change, giving false comfort.

Python Unit-test a policy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The third case deserves thought: should a bucket with no public field pass? A stricter policy might require the field to be present and equal to False. Deciding on such defaults, "deny unless proven safe" versus "allow unless proven unsafe", is a core design choice. For security rules, prefer the first.

Good practice

  • Start in audit mode (report only), fix the findings, then switch to enforce.
  • Give clear messages with the rule, the resource and how to fix it, and link to documentation.
  • Allow exceptions deliberately: time-limited, approved, recorded in code and reviewed.
  • Keep policies in version control with owners, reviews and tests, and roll out changes gradually.
  • Layer your defences: pipeline checks give fast feedback, admission control is the hard stop, and audits catch drift from manual changes and from resources that bypassed the pipeline.
  • Do not ignore the cloud's own guardrails. Organisation-level policies can prevent entire classes of mistakes even in accounts that nobody remembers.

See also Kubernetes security basics for admission control, and compliance frameworks for the rules that policies often encode.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of policy as code?

    Machine-readable rules can be applied on every change, versioned and tested, which written policies cannot.
  2. 2. Which tool is Kubernetes-native and defines policies as YAML resources?

    Kyverno policies are Kubernetes custom resources. OPA Gatekeeper uses Rego for similar enforcement.
  3. 3. Why is it a good idea to start a new policy in audit mode?

    Switching on enforcement immediately can break teams. Audit mode shows the impact first.
  4. 4. Which design is safer for a security rule about public access?

    Deny by default fails safe: a missing or malformed field is treated as a violation, not a pass.

Summary

  • Policy as code turns written rules into automatic checks that run in pull requests, pipelines, admission controllers and audits.
  • OPA/Rego, Kyverno, Sentinel, IaC scanners and cloud guardrails are the main tools.
  • A policy engine is policies plus inputs plus a runner; messages must explain the violation.
  • Test policies, start in audit mode, handle exceptions explicitly and prefer deny-by-default.

Next: Posture Management and Misconfiguration