Policy as Code

Express security and compliance rules as versioned code and enforce them automatically in pipelines and clusters.

AdvancedPolicy as CodeGovernanceInfrastructureContainer

Where it fits in the lifecycle

  1. Plan
  2. Code
  3. Build
  4. Test
  5. Release
  6. Deploy
  7. Operate
  8. Monitor
  • Build Dependency scanning, image scanning, SBOM generation and signing.
  • Deploy Policy enforcement, admission control and infrastructure security.

Overview

Policy engines evaluate structured input — a Kubernetes admission request, a Terraform plan, a JSON config — against declarative rules. The same policy can run in CI and at admission time, so the rule and the enforcement point stay consistent.

Why it matters

Written policies that live in a wiki are not enforced. Encoding them makes compliance testable, reviewable and continuously applied.

How it works

  1. 01Policies are written in Rego or a YAML policy language and stored in git.
  2. 02CI evaluates manifests and plans against the policies.
  3. 03An admission controller enforces the same policies in the cluster.
  4. 04Violations are reported with the rule identifier and remediation text.

Common tools

Open Policy AgentKyvernoConftestGatekeeperKubernetesOpenShiftTerraform

Implementation examples

yamlKyverno policy: disallow latest tag
apiVersion: kyverno.io/v1kind: ClusterPolicymetadata:  name: disallow-latest-tagspec:  validationFailureAction: Audit  rules:    - name: require-image-tag      match:        any:          - resources:              kinds: [Pod]      validate:        message: "An explicit image tag is required."        pattern:          spec:            containers:              - image: "!*:latest"
Start in Audit mode, review the reported violations, then switch to Enforce once the noise is understood.
bashTest manifests in CI with Conftest
conftest test --policy policies/ k8s/
Runs the same rule set before the manifest ever reaches the cluster.

Best practices

  • Roll out in audit mode first and measure violation volume.
  • Unit-test policies with fixtures for allow and deny cases.
  • Version policies and require review like application code.

Common mistakes

  • Enforcing immediately and breaking existing workloads.
  • Writing policies without exemption mechanisms for legitimate cases.

Hands-on labs