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
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.
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.
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.
Three questions. No score is saved anywhere — this is just you against the material.
Cloud governance grows in four levels: reading policies and findings, writing policies as code, building automated reviews, and running governance as a product.
At the basic level you know the rules your changes must meet and can fix a failed check.
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.
At the intermediate level you turn written rules into checks.
Try it: Intermediate
What makes a policy-as-code rule good?
Now do it: Write one Rego rule with two tests.
At the advanced level reviews collect their own evidence.
Try it: Advanced
Which changes should go to a human architect?
Now do it: Write your risk-routing rules.
At the master level governance is measured like a product its users depend on.
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.
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).
This is a composite of a failure pattern that keeps repeating; the details are illustrative. The rule that lived in a PDF.
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.
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.
Type each one, read what it prints, and compare it with the note above it.
Write a small plan file with one public bucket and one bucket without an owner tag.
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": {}}}}
]}
EOFWrite the policy in Rego, the language OPA and Conftest use.
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])
}
EOFRun the policies against the plan, as CI would.
conftest test plan.json --policy policy/; echo "exit code $?"
governance.pyThis 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
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
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
mkdir, cat, echo, cd, Redirection, If...Else, Here documents, Exit codes.A company with 70 teams has a 200-page cloud policy, a monthly architecture board, and frequent audit findings. Design its governance.
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?
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.
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.
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.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Policy only on paper | Hop 2: Policy as code in CI | Breaks | The 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 board | Hop 8: Human review | Breaks | Every 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. |
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.
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.
| Choice | Gains | Costs |
|---|---|---|
| Checks in the pipeline (Checkov, Conftest on plans) | Fast feedback before deploy | Only sees what goes through the pipeline |
| Cloud-side policies (Config, Azure Policy, org policies) | Catches drift and manual changes | Feedback after the fact |
| Deny versus audit | Deny prevents; audit informs | Deny can block work; start in audit, then deny |
| Signal | Measured by | Alert when |
|---|---|---|
| Non-compliant resources | Count per rule and team | A count that rises week on week |
| Exceptions | Open exceptions and their expiry | Any expired exception |
| Pipeline blocks | Changes blocked per rule | A rule blocking often (it may be wrong) |
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.
aws configservice describe-compliance-by-config-rule --compliance-types NON_COMPLIANTaz policy state list --filter "complianceState eq 'NonCompliant'" --top 20 --output tablegcloud resource-manager org-policies list --project=PROJECTcheckov -f plan.json --framework terraform_plan --compactThe 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.
Then review it against the ten general areas below.
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.
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.