Most cloud compliance rules still live in documents and spreadsheets, so they are checked weeks after a misconfigured resource has already shipped. Security policy as code turns those rules into versioned, tested code that runs at every point where infrastructure changes: in the pull request, at the deployment gate, at the Kubernetes API server and at the cloud organisation level. This guide covers compliance and configuration guardrails, not authorisation decisions about who may call which API, which the Policy-as-Code for Authorisation Guide covers. It is for cloud platform engineers, compliance engineers and the security architects who own the control catalogue. Tools and platforms are listed alphabetically throughout; order is never a ranking.
Key takeaways
- One rule, several enforcement points. The same intent (for example "storage must not be public") should be checked in the IaC scan, at the deployment gate, at admission or the cloud API, and again by a detective scan, because each point misses changes the others catch.
- Policies are software and need tests. Every rule needs passing and failing fixtures, a CI job that runs them, and a check that fails the build when no tests ran.
- Start in warn or audit mode. Every major engine has a non-blocking mode (dryrun, warn, Audit, advisory); use it to measure impact before you block.
- Exceptions are code too. Waivers belong in the repository or the platform's exemption object, with an owner, a reason, a ticket and an expiry date, and they should be reported as a separate count.
- Map every rule to a control ID. Rule metadata that names the NIST SP 800-53, CIS or ISO/IEC 27001 control lets the pipeline produce audit evidence as a by-product.
What security policy as code means
Security policy as code is the practice of expressing configuration and compliance requirements as machine-readable rules, stored in version control, reviewed like application code, and evaluated automatically against infrastructure definitions and live resources. The rule "S3 buckets must have versioning enabled" stops being a line in a hardening standard and becomes a test that fails a pipeline.
It differs from authorisation policy as code in what it evaluates and when:
| Aspect | Compliance guardrails (this guide) | Authorisation policy |
|---|---|---|
| Question answered | Is this resource or change configured acceptably? | May this principal perform this action on this resource now? |
| Input | IaC files, plans, Kubernetes manifests, cloud API requests, resource inventories | Request context: principal, action, resource, attributes |
| When it runs | Commit, pull request, deploy, admission, periodic scan | Every request at run time |
| Typical owner | Platform, cloud and compliance engineering | Application and identity teams |
| Failure mode | Blocked deployment or recorded violation | Denied request |
Some engines serve both purposes. Open Policy Agent (OPA) and its Rego language power Conftest for files and Gatekeeper for Kubernetes admission as well as authorisation services; see Open Policy Agent in Production for running the engine itself.
Where guardrails run
Each enforcement point sees a different slice of change. A rule enforced only in CI misses console changes; a rule enforced only at the cloud API gives developers feedback far too late. The table lists common mechanisms by point, with each tool's own non-blocking mode.
| Enforcement point | What it sees | Example mechanisms | Non-blocking mode | What it misses |
|---|---|---|---|---|
| Developer and pull request (IaC scan) | Terraform, CloudFormation, Kubernetes YAML, Helm output, Dockerfiles | AWS CloudFormation Guard (cfn-guard), Checkov, Conftest | Report-only CI job, Conftest warn rules, soft fail flags | Changes made outside the repository; values only known at apply time |
| Deployment gate (plan or stack) | Resolved Terraform plans, CloudFormation change sets and stack operations | AWS Control Tower proactive controls (CloudFormation hooks), HashiCorp Sentinel in HCP Terraform, OPA against plan JSON | Sentinel advisory level; hook in warn mode | Direct API, console and SDK changes |
| Kubernetes admission | Every create and update request to the API server | Gatekeeper, Kubernetes ValidatingAdmissionPolicy, Kyverno | Gatekeeper dryrun and warn; VAP and Kyverno Warn and Audit | Cloud resources outside the cluster |
| Cloud organisation policy | API requests in every account, subscription or project, whatever the tool | AWS SCPs and RCPs, Azure Policy deny effects, Google Cloud organisation policy constraints | Azure enforcementMode DoNotEnforce or audit effect; Google Cloud dry run | Settings the provider does not expose as a condition |
| Detective scan | Deployed state, including drift and legacy resources | AWS Config rules, Azure Policy compliance, CSPM tools, Guard against configuration items | Always non-blocking; may trigger remediation | Nothing in scope, but it finds problems after exposure |
Two caveats from vendor documentation shape the design. AWS states that Control Tower proactive controls act on CloudFormation stack create and update operations and may not affect requests made directly through the console, APIs, SDKs or other IaC tools, so they complement rather than replace preventive controls. Cloud organisation policies are the only point that covers every path, which is why their rollout needs its own method: see the Preventive Cloud Guardrails Guide. For admission design choices see the Kubernetes Admission Control Guide, and for scanner selection the Checkov and IaC Scanners Guide.
Choosing the points for a rule
- Catastrophic and cheap to express: enforce at the cloud organisation level (blocking) and scan in pull requests for early feedback. Example: no public storage outside an approved account.
- Workload configuration in Kubernetes: admission control in Deny mode, with the same rule run by Conftest or the engine's CLI in CI so developers see failures before deploy.
- Context-dependent rules (tagging, encryption key choice, approved images): pull request and deployment gate, plus a detective scan to catch drift.
- Small organisations: a single IaC scanner in CI plus the provider's built-in organisation policies covers most risk. Add admission control when you run shared clusters.
- Large organisations: keep a central policy library with one rule ID per intent and per-engine implementations, so a change to the intent updates every point together.
Writing and testing policies
Treat the policy repository as a product. A rule that blocks a valid deployment costs developer trust; a rule that silently passes everything is worse, because it produces false assurance.
Rule design
- One intent per rule, with a stable ID: Conftest documents that
deny,violationandwarnrules can carry an identifier suffix such asdeny_run_as_root, which also enables targeted exceptions. Use the same ID in the engine, the exception register and the control mapping. - Actionable messages: the failure message should name the resource, the setting and the fix, plus a link to the internal standard.
- Parameters, not copies: Gatekeeper constraint templates and ValidatingAdmissionPolicy parameter resources let one rule serve many scopes with different values (allowed registries, required labels).
- Fail closed deliberately: for admission, decide the failure behaviour when the policy engine is unavailable. ValidatingAdmissionPolicy applies
failurePolicy; a webhook engine that fails open removes the guardrail during an outage.
Test practices
- Unit tests per rule: OPA runs rules prefixed
test_withopa test; Conftest runs the same style of tests withconftest verify; cfn-guard has a built-in unit testing framework; Kyverno ships akyverno testcommand. Every rule needs at least one passing and one failing fixture. - Guard against empty runs: OPA documents that
opa teststill succeeds when no tests run, for example after a misspelt test name, unless you add--fail-on-empty. Add it in CI. - Measure coverage:
opa test --coveragereports evaluated and unevaluated lines per file. Set a floor for the library and block merges that reduce it. - Golden fixtures from real code: keep a corpus of real (sanitised) Terraform plans and manifests from production repositories, and run every policy change against it to see how many existing resources would newly fail.
- Shadow in production: deploy new rules non-blocking (Gatekeeper
enforcementAction: dryrun, where impacted resources appear as violations in the constraint status; VAPvalidationActions: [Warn, Audit]; Sentinel advisory). Kubernetes does not allowDenyandWarntogether on one binding. - Promote with a change record: move from audit to blocking only when the violation count in shadow mode is zero or every remaining violation has an approved exception.
- Roll back fast: keep the previous policy bundle version tagged, and make the switch back to non-blocking a single reviewed change.
Exceptions and waivers
Every guardrail programme needs exceptions. The failure is not having them; it is having exceptions nobody can list, that never expire, or that exempt whole rule sets when one rule was the problem.
| Mechanism | How an exception is expressed | Built-in governance aids |
|---|---|---|
| Azure Policy | Exemption resource against an assignment, optionally listing specific policyDefinitionReferenceIds in an initiative | exemptionCategory Mitigated or Waiver; expiresOn date after which the exemption is no longer honoured but kept for records; free-form metadata (for example requester, approver, ticket) |
| Checkov | Inline checkov:skip=<check_id>:<reason> comment in the resource block, or run and skip lists | Skipped checks appear as SKIPPED with the suppression comment in output |
| Conftest | Rego exception rule naming the exempted rule IDs for matching inputs | Exceptions are reported as a separate tally in the summary |
| HashiCorp Sentinel | Override of a soft mandatory policy by a privileged user | Override creates a record of who bypassed the failure; hard mandatory cannot be overridden except by removing the policy |
| Kyverno | Namespaced PolicyException referencing the policy and rule, with match conditions | Off by default (enablePolicyException), limited to namespaces set by exceptionNamespace; matches show as skip results in PolicyReports |
A governance model that holds
- Request: a ticket naming the rule ID, the exact resources, the business reason and any compensating control.
- Approve: the control owner approves, not the requester's own team; high-severity rules need the security architect.
- Express narrowly: exempt one rule for named resources, never a whole initiative, namespace or account where a narrow match is possible. Conftest warns that an empty-string exception matches all
denyandviolationrules. - Protect the exception path: restrict who can merge to the exception file or create exemption objects (repository CODEOWNERS, Kubernetes RBAC on PolicyException, cloud role assignments on exemptions). An exception path anyone can write to is an off switch.
- Expire: default 90 days, renewable once with fresh approval. Fail the pipeline when an exception has passed its expiry date in a format the engine does not enforce itself.
- Report: count active exceptions per rule and per team monthly. A rule with many exceptions is usually a badly written rule.
Exceptions map naturally to risk acceptance and plans of action: NIST SP 800-53 RA-7 (Risk Response) and CA-5 (Plan of Action and Milestones).
Mapping to compliance controls
Policy as code earns its keep with auditors when each rule carries metadata naming the controls it implements. Conftest and OPA support metadata annotations on rules, and Gatekeeper constraints and Kyverno policies take labels and annotations; use these to hold a control ID list. The pipeline then emits, for every run, the rule, the control, the resources evaluated and the result.
| Framework | Control | How policy as code supports it |
|---|---|---|
| NIST SP 800-53 Rev 5 | CM-2 Baseline Configuration; CM-6 Configuration Settings | Rules are the machine-readable baseline; results evidence that settings are applied |
| NIST SP 800-53 Rev 5 | CM-3 Configuration Change Control; CM-4 Impact Analyses | Policy checks in pull requests and plans gate changes; shadow-mode results show impact before enforcement |
| NIST SP 800-53 Rev 5 | CM-7 Least Functionality | Rules block unapproved services, ports, regions and images |
| NIST SP 800-53 Rev 5 | CA-7 Continuous Monitoring; SA-11 Developer Testing and Evaluation | Detective scans and CI policy tests run on every change |
| NIST SP 800-53 Rev 5 | RA-7 Risk Response; CA-5 Plan of Action and Milestones | Exception register with owner, reason and expiry |
| NIST CSF 2.0 | PR.PS-01; GV.PO-01; DE.CM-09 | Configuration management applied and enforced; policy communicated and enforced; runtime monitoring |
| CIS Controls v8.1 | Control 4 Secure Configuration of Enterprise Assets and Software | Secure configuration expressed and enforced as code |
| ISO/IEC 27001:2022 Annex A | A.8.9 Configuration management; A.8.32 Change management | Versioned baselines and gated changes with recorded results |
Be careful with vendor "compliance packs" that claim to cover a framework. They map checks to controls, but a passing check usually evidences one part of a control, not the whole of it. Keep your own mapping and record which control parts remain manual. For producing and organising evidence see the Audit Evidence Request Tracker Template.
Operating at scale
Phased rollout
- Inventory rules: list the 20 to 40 configuration requirements that matter most from your standards and recent audit findings. Give each an ID, an owner and a severity.
- Pick engines per point: one IaC scanner, one admission engine, the cloud provider's organisation policy. Avoid running two admission engines that enforce the same rule differently.
- Report-only everywhere: run in CI as a non-failing job and in clusters in audit mode for two to four weeks. Publish results per team.
- Block the top tier: enforce critical rules first, with the exception path live on the same day.
- Expand in rings: sandbox accounts and non-production clusters, then a pilot group, then production.
- Close the loop: feed detective findings back into new preventive rules, and retire rules with no violations and no residual risk.
Where identity fits
Policy pipelines run on non-human identities: CI runners that read plans, admission webhooks with cluster-wide read access, and service principals that create exemptions. Give the pipeline identity read-only rights where it only evaluates, protect any identity that can disable enforcement or write exemptions as privileged, and use workload identity federation rather than stored keys for CI. See the Terraform and IaC Pipeline Credential Security Guide.
Detection and measurement
- Enforcement coverage: percentage of critical rules enforced at two or more points.
- Policy test health: rule coverage from
opa test --coverageor equivalent, and the share of rules with both passing and failing fixtures. - Shadow-to-enforce time: median days a rule spends in audit mode before blocking.
- Active exceptions: count per rule and per team, and the number past expiry (target: zero).
- Drift rate: detective findings for rules that are also enforced preventively, which reveals bypass paths.
- Enforcement tampering: alert on changes to admission webhook configurations, Gatekeeper constraints, Kyverno policies, Azure Policy assignments and organisation policies outside the policy pipeline.
Common failure patterns
- CI-only enforcement: rules exist in the pipeline but nothing stops a console or CLI change, so drift accumulates unseen.
- Silent test suites: a renamed package means zero tests run and CI stays green; fix with
--fail-on-emptyand coverage floors. - Blanket exceptions: an exemption for a whole namespace or initiative to unblock one resource, never revisited.
- Webhook failing open: the admission engine goes down and every request is admitted, unnoticed because no alert watches the engine's health.
- Divergent rule copies: the IaC rule and the admission rule for the same intent drift apart, so a resource passes CI and fails at deploy, and developers learn to ignore both.
- Compliance theatre: a dashboard at 98 percent passing against a vendor pack whose checks only touch a fraction of each control.
Practitioner checklist
- Give every guardrail a stable rule ID, owner, severity and mapped control IDs.
- Enforce each critical rule at two or more points, one of them independent of the IaC pipeline.
- Require passing and failing fixtures for every rule, and run tests with an empty-run failure flag and a coverage floor.
- Release every new rule in dryrun, warn, Audit or advisory mode first and record the violation count.
- Keep exceptions narrow, owned, ticketed and dated, in the repository or the platform exemption object.
- Restrict who can write exceptions or change enforcement mode, and alert on changes outside the pipeline.
- Decide and test admission failure behaviour when the policy engine is unavailable.
- Report coverage, exceptions and drift monthly to the control owners.
Standards and references
- NIST: SP 800-53 Rev. 5 Security and Privacy Controls
- Kubernetes: Validating Admission Policy
- Open Policy Agent: Policy Testing
- Conftest: Exceptions
- Gatekeeper: Handling Constraint Violations
- Kyverno: Policy Exceptions
- HashiCorp: Sentinel Enforcement Levels
- Microsoft Learn: Azure Policy Exemption Structure
Related NHI Mgmt Group resources: Policy-as-Code for Authorisation Guide · Preventive Cloud Guardrails Guide · Kubernetes Admission Control Guide · Cloud Security Posture Management (CSPM) Guide