Platform Engineering · Lesson 174

Cloud Governance, Policy as Code, and Automated Architecture Reviews

Cloud governance is how an organisation makes sure hundreds of teams build in the cloud safely, within budget, and within the rules, without a review board in the way of every change. It works in layers: policies written down, encoded as policy as code that runs in pipelines (before deployment) and in the cloud (at deployment and continuously), exceptions with owners and expiry dates, and architecture reviews that are partly automated so humans spend their time on judgement. This lesson follows one infrastructure change from pull request to production, and shows two governance failures: a policy that existed only in a document, and a review gate so slow that teams went around it.

Difficulty: Master · Know this first: Lesson 173, Lesson 148

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes from pull request to approved deployment. It is a worked example, not a measurement. The policy-as-code and human review hops decide whether governance protects or obstructs.

Try it: design the governance

Pick where policies are enforced, how reviews work, and how exceptions are handled. The readouts show lead time for a change and what slips through.

74 minlead time for a change
nonewhat slips through

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Cloud governance grows in four levels: reading policies and findings, writing policies as code, building automated reviews, and running governance as a product.

Basic — Read policies and findings

At the basic level you know the rules your changes must meet and can fix a failed check.

  • The policy catalogue: rule, reason, owner, enforcement.
  • Policy results on your pull request; compliance findings for your team.
  • How to request an exception.

Where it breaks: treating a failed policy check as an obstacle rather than information.

Try it: Basic

Your pull request fails "storage must be encrypted with a customer-managed key". What do you do first?

Now do it: Fix one failing policy in a test change.

Intermediate — Write policies as code

At the intermediate level you turn written rules into checks.

  • Rego for Conftest or Gatekeeper; Checkov custom checks; Azure Policy or Org Policy definitions.
  • Tests for each policy (a passing and a failing example).
  • Messages that say what to change and why.

Try it: Intermediate

What makes a policy-as-code rule good?

Now do it: Write one Rego rule with two tests.

Advanced — Automated architecture reviews

At the advanced level reviews collect their own evidence.

  • A review bot gathering plan, policy, cost, SLO, threat model, backup, and ownership evidence.
  • Scoring against the ten review areas; flags routed by risk.
  • Continuous compliance findings routed to owners with severity deadlines.

Try it: Advanced

Which changes should go to a human architect?

Now do it: Write your risk-routing rules.

Master — Governance as a product

At the master level governance is measured like a product its users depend on.

  • Lead time for changes through governance; share passing first time; exception age.
  • Policies versioned and rolled out progressively (audit first, then enforce).
  • Evidence stored for audits; frameworks mapped to policies automatically.

Trade-off: every policy adds friction; retire rules that no longer pay for themselves, and keep the catalogue short enough that people know it.

Try it: Master

How do you roll out a new deny policy without breaking teams?

Now do it: Plan an audit-then-enforce rollout for one rule.

Go deeper

A Rego policy for Conftest that rejects public or unencrypted S3 buckets in a Terraform plan (Rego v1 syntax; check your OPA version):

package main

import rego.v1

deny contains msg if {
  some rc in input.resource_changes
  rc.type == "aws_s3_bucket_public_access_block"
  some field in ["block_public_acls", "block_public_policy", "ignore_public_acls", "restrict_public_buckets"]
  rc.change.after[field] == false
  msg := sprintf("%s: %s must be true (policy STOR-01: no public buckets; customer data has leaked this way)", [rc.address, field])
}

deny contains msg if {
  some rc in input.resource_changes
  rc.type == "aws_s3_bucket"
  not rc.change.after.tags.owner
  msg := sprintf("%s: an owner tag is required (policy GOV-02: every resource has an owner)", [rc.address])
}
terraform plan -out tfplan && terraform show -json tfplan > plan.json
conftest test plan.json --policy policy/          # fails the pipeline with the messages above
checkov -f plan.json --framework terraform_plan   # a second scanner with hundreds of built-in checks
infracost breakdown --path plan.json              # the cost evidence for the review

Where each layer runs, per cloud: pipelines (any CI) with OPA/Conftest, Checkov, or Sentinel; preventive guardrails (SCPs and resource control policies, Azure Policy deny, Organization Policy constraints); detective scanning (AWS Config and Security Hub, Azure Policy compliance and Defender for Cloud, Security Command Center); Kubernetes admission (Gatekeeper, Kyverno, ValidatingAdmissionPolicy).

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The rule that lived in a PDF.

Timeline

  • Week 0A team adds a bucket for partner data exports with a public-read policy, so the partner can download without credentials. CI has no storage policies; account-level Block Public Access is not enabled.
  • Week 0–3A Config rule flags the bucket on a dashboard nobody watches.
  • Week 3An external researcher reports that customer exports are downloadable. The bucket is closed within the hour; access logs are analysed; affected customers are notified.
  • Week 4The rule is encoded in Conftest, Block Public Access is enforced at every account with an SCP preventing its removal, and Config findings route to owners with a 24-hour deadline for critical ones.

What changed after

Every policy in the catalogue lists its enforcement points; a policy with none is not considered in force. Partner sharing uses pre-signed URLs or a transfer service under an approved pattern.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: The conftest binary from its GitHub releases page (it bundles OPA), and Python 3. No cloud account is needed: the plan below is a small JSON file in the shape terraform show -json produces.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Write a small plan file with one public bucket and one bucket without an owner tag.

    Reversible

    mkdir -p ~/labs/gov/policy && cd ~/labs/gov
    cat > plan.json <<'EOF'
    {"resource_changes": [
      {"address": "aws_s3_bucket.exports", "type": "aws_s3_bucket", "change": {"after": {"tags": {"owner": "data"}}}},
      {"address": "aws_s3_bucket_public_access_block.exports", "type": "aws_s3_bucket_public_access_block",
       "change": {"after": {"block_public_acls": true, "block_public_policy": false, "ignore_public_acls": true, "restrict_public_buckets": false}}},
      {"address": "aws_s3_bucket.scratch", "type": "aws_s3_bucket", "change": {"after": {"tags": {}}}}
    ]}
    EOF

    Expect: A plan.json file; nothing else happens.

    Clean up: rm -rf ~/labs/gov.

  2. Write the policy in Rego, the language OPA and Conftest use.

    Reversible

    cat > policy/storage.rego <<'EOF'
    package main
    import rego.v1
    deny contains msg if {
      some rc in input.resource_changes
      rc.type == "aws_s3_bucket_public_access_block"
      some f in ["block_public_acls", "block_public_policy", "ignore_public_acls", "restrict_public_buckets"]
      rc.change.after[f] == false
      msg := sprintf("%s: %s must be true (STOR-01: no public buckets)", [rc.address, f])
    }
    deny contains msg if {
      some rc in input.resource_changes
      rc.type == "aws_s3_bucket"
      not rc.change.after.tags.owner
      msg := sprintf("%s: owner tag required (GOV-02)", [rc.address])
    }
    EOF

    Expect: A policy/storage.rego file with two rules, each with an ID and a reason in its message.

  3. Run the policies against the plan, as CI would.

    Read-only

    conftest test plan.json --policy policy/; echo "exit code $?"

    Options: --policy is the folder of Rego files; a non-zero exit code fails the pipeline.

    Expect: Three FAIL lines (two public-access fields and the missing owner tag) and exit code 1.

2. Python: governance.py

This program checks a Terraform plan against policies with IDs and reasons, honours exceptions only while they are unexpired and owned, and produces an automated architecture review score across the ten review areas from the evidence attached to the change, routing what is missing to a human. Save it as governance.py, then run it.

# governance.py
from datetime import date

TODAY = date(2026, 11, 27)
PLAN = [
    {"address": "aws_s3_bucket.exports", "type": "bucket", "public": True, "encrypted": True, "owner": "data"},
    {"address": "aws_s3_bucket.sftp_partner", "type": "bucket", "public": True, "encrypted": True, "owner": "integrations"},
    {"address": "aws_db_instance.orders", "type": "database", "public": False, "encrypted": False, "owner": "orders"},
    {"address": "aws_s3_bucket.scratch", "type": "bucket", "public": False, "encrypted": True, "owner": None},
]
POLICIES = [
    ("STOR-01", "no public storage", lambda r: r["type"] == "bucket" and r["public"]),
    ("ENC-01", "encryption at rest", lambda r: not r["encrypted"]),
    ("GOV-02", "every resource has an owner", lambda r: not r["owner"]),
]
EXCEPTIONS = {  # (policy, resource): (owner, expires, reason)
    ("STOR-01", "aws_s3_bucket.sftp_partner"): ("integrations-lead", date(2027, 2, 1), "partner pulls by IP allow-list; data is public catalogue only"),
    ("ENC-01", "aws_db_instance.orders"): ("orders-lead", date(2026, 10, 1), "legacy engine"),
}

failures = 0
for r in PLAN:
    for pid, name, violates in POLICIES:
        if not violates(r):
            continue
        exc = EXCEPTIONS.get((pid, r["address"]))
        if exc and exc[1] >= TODAY:
            print(f"EXCEPTION {pid} {r['address']}: allowed until {exc[1]} by {exc[0]} ({exc[2]})")
            continue
        failures += 1
        why = f"exception expired {exc[1]}" if exc else name
        print(f"FAIL      {pid} {r['address']}: {why}")
print(f"policy check: {'FAIL' if failures else 'PASS'} ({failures} violations)\n")

EVIDENCE = {"business outcome": "linked ticket with KPI", "security": "policy results, threat model v2",
            "reliability": "SLO 99.9% defined", "performance": "load test at 2x peak",
            "operations": "dashboards and runbook", "cost": "Infracost +$1,840/month, within budget",
            "sustainability": "ARM instances, lifecycle rules", "governance": None,
            "ownership": "owner tags and on-call", "failure and recovery plan": None}
covered = [a for a, e in EVIDENCE.items() if e]
print(f"automated review: {len(covered)} of {len(EVIDENCE)} areas have evidence")
for area, e in EVIDENCE.items():
    if not e:
        print(f"  needs a human: {area}")

Run it, and you should see this output:

$ python3 governance.py
FAIL      STOR-01 aws_s3_bucket.exports: no public storage
EXCEPTION STOR-01 aws_s3_bucket.sftp_partner: allowed until 2027-02-01 by integrations-lead (partner pulls by IP allow-list; data is public catalogue only)
FAIL      ENC-01 aws_db_instance.orders: exception expired 2026-10-01
FAIL      GOV-02 aws_s3_bucket.scratch: every resource has an owner
policy check: FAIL (3 violations)

automated review: 8 of 10 areas have evidence
  needs a human: governance
  needs a human: failure and recovery plan

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/cloud-governance-and-architecture-review-automation && cd ~/labs/cloud-governance-and-architecture-review-automation) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Cloud Governance, Policy as Code, and Automated Architecture Reviews", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Write a small plan file with one public bucket and one bucket without an owner tag.'
  'Write the policy in Rego, the language OPA and Conftest use.'
  'Run the policies against the plan, as CI would.'
)

step_1() {
mkdir -p ~/labs/gov/policy && cd ~/labs/gov
cat > plan.json <<'EOF'
{"resource_changes": [
  {"address": "aws_s3_bucket.exports", "type": "aws_s3_bucket", "change": {"after": {"tags": {"owner": "data"}}}},
  {"address": "aws_s3_bucket_public_access_block.exports", "type": "aws_s3_bucket_public_access_block",
   "change": {"after": {"block_public_acls": true, "block_public_policy": false, "ignore_public_acls": true, "restrict_public_buckets": false}}},
  {"address": "aws_s3_bucket.scratch", "type": "aws_s3_bucket", "change": {"after": {"tags": {}}}}
]}
EOF
}

step_2() {
cat > policy/storage.rego <<'EOF'
package main
import rego.v1
deny contains msg if {
  some rc in input.resource_changes
  rc.type == "aws_s3_bucket_public_access_block"
  some f in ["block_public_acls", "block_public_policy", "ignore_public_acls", "restrict_public_buckets"]
  rc.change.after[f] == false
  msg := sprintf("%s: %s must be true (STOR-01: no public buckets)", [rc.address, f])
}
deny contains msg if {
  some rc in input.resource_changes
  rc.type == "aws_s3_bucket"
  not rc.change.after.tags.owner
  msg := sprintf("%s: owner tag required (GOV-02)", [rc.address])
}
EOF
}

step_3() {
conftest test plan.json --policy policy/; echo "exit code $?"
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

A company with 70 teams has a 200-page cloud policy, a monthly architecture board, and frequent audit findings. Design its governance.

Clarifying questions to ask

Which policies are encoded first, and where does each run? How are exceptions handled? What does the automated review collect and score? Which changes need a human, and how fast? How are findings routed? How do you measure whether governance helps or hinders?

Rough sizing

Say 70 teams, 300 changes a week, 4 cloud accounts per team on average, PCI DSS scope for one product, and a 6-week board backlog.

Shape of the answer

A policy catalogue cut to about 40 rules with reasons and owners; the top 15 encoded in Conftest and Checkov on Terraform plans and in Gatekeeper for Kubernetes, the critical ones also as SCPs, Azure Policy, and Org Policy; continuous scanning with findings routed by owner tag and severity deadlines; exceptions as code with expiry; a review bot that gathers plan, policy, cost, SLO, threat model, backup, and ownership evidence and scores the ten areas; risk-based routing so high-risk changes reach an architect within a day; evidence stored per commit; metrics on lead time, first-time pass rate, and exception age.

Trade-offs to name

Encoding policies takes engineering time and catches problems early; double enforcement adds a little friction and closes the console gap; removing the board loses some cross-team conversation, which a weekly open design forum can replace.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Policy only on paperHop 2: Policy as code in CIBreaksThe bucket rule exists only on paper. A pull request adds a bucket for data exports with a public-read policy "for the partner to download". Nothing checks it.
Six-week review boardHop 8: Human reviewBreaksEvery change waits for a monthly architecture board; the average wait is six weeks. Teams start building in a sandbox account by hand "to prototype", and two services go live from there.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Written policy → Policy as code in CI → Plan check → Cloud guardrail → Continuous compliance → Exceptions → Automated review → Human review → Evidence. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

Architecture framework

This design, the way an architecture review would take it apart. The animated diagram near the top of the page shows the path a request takes, the Design exercise asks you to make the main decisions, Failure modes lists what breaks, and the hands-on lab builds part of it on your machine. This section adds the rest.

Design problem

Architecture reviews are a monthly meeting that slows teams down and still misses problems. Turn the rules into code that checks every change, and keep the board for the hard decisions.

Constraints

Trade-offs

ChoiceGainsCosts
Checks in the pipeline (Checkov, Conftest on plans)Fast feedback before deployOnly sees what goes through the pipeline
Cloud-side policies (Config, Azure Policy, org policies)Catches drift and manual changesFeedback after the fact
Deny versus auditDeny prevents; audit informsDeny can block work; start in audit, then deny

Security boundaries

Cost

Observability plan

SignalMeasured byAlert when
Non-compliant resourcesCount per rule and teamA count that rises week on week
ExceptionsOpen exceptions and their expiryAny expired exception
Pipeline blocksChanges blocked per ruleA rule blocking often (it may be wrong)

Disaster recovery plan

RPO
Policies and exceptions are in Git: no loss.
RTO
Minutes to re-apply policies from code.
Strategy
Policies as code, applied by a pipeline to every account or subscription.
Test
Apply the policy set to a fresh test account and confirm the expected denials.

Runbook commands

Read-only: each one shows state and changes nothing. They run against a real account with the provider named, so the course does not run them for you; replace the words in capitals with your own names.

  1. Which Config rules have non-compliant resources?AWS
    aws configservice describe-compliance-by-config-rule --compliance-types NON_COMPLIANT
  2. Which resources are non-compliant?Azure
    az policy state list --filter "complianceState eq 'NonCompliant'" --top 20 --output table
  3. Which organisation policies apply to this project?Google Cloud
    gcloud resource-manager org-policies list --project=PROJECT
  4. What does the policy say about this Terraform plan? (local)Any shell
    checkov -f plan.json --framework terraform_plan --compact

Validation and cleanup

The runbook commands change nothing, so there is nothing to undo after them. The lab ends with its own check and cleanup step. If you build this design in a real account, create it with infrastructure as code, check it with the runbook commands, then remove it with the same tool (for example terraform destroy) and look at the billing page the next day.

Checklist for this design

Then review it against the ten general areas below.

Architecture review checklist

Review the design in this lesson, or your own, against these ten areas. Tick an area when you can answer its question with evidence: a number, a test, a document, or an owner. Your ticks stay in this browser.

  1. Business outcomeWhich result for users or the business does this design serve, and which number shows it is working?
  2. SecurityWho and what can reach each part, how is identity proven, and how is data protected in transit and at rest?
  3. ReliabilityWhat is the target (SLO), which single failures does the design survive, and how was that tested?
  4. PerformanceWhat latency and throughput are required at peak, and where is the first bottleneck?
  5. OperationsHow is it deployed, observed, and changed safely, and who is paged when it breaks?
  6. CostWhat does it cost per month and per unit of work (request, tenant, model call), and what grows the bill?
  7. SustainabilityWhich resources sit idle, which region and hardware does it run on, and what can scale to zero?
  8. GovernanceWhich policies, guardrails, and compliance rules apply, and how are they enforced in code?
  9. OwnershipWhich team owns each component, its budget, and its on-call, and where is that written down?
  10. Failure and recovery planWhat is the RTO and RPO, what is the runbook for a region or dependency loss, and when was it last rehearsed?

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 175
Jenkins

Lesson 98 gave you the pipeline. This lesson gives you the tool that has run more pipelines than any other. Jenkins is a controller that watches your repo, and agents that do the work. A push lands.

Go to Lesson 175 →

Or browse the full course from the Lessons index.