// Why this matters
Managing GCP organisation policy as code, with admission control in the cluster and delivery metrics beside it, is how a platform team gives many teams freedom without giving up a baseline. Guardrails say what cannot happen; metrics tell you whether the guardrails slow people down.
The engineering approach is to treat policy as data. A list of constraints with scopes and rules is easier to review than hand-written resources, and a new constraint becomes a three-line diff rather than a new module.
Metrics close the loop. If you ship controls without measuring lead time and failure rate, you cannot tell the difference between a platform that helps and one that merely constrains. This post pairs naturally with The GCP Project Factory: Folder, Project, VPC and GKE per Tenant and Cloud Governance as Code with Cloud Custodian.
// The problem
With many projects and clusters, a baseline of controls drifts. One project allows external IPs on VMs because someone needed it for a test; one cluster has a public load balancer that nobody remembers creating. Every exception is reasonable at the time and invisible a year later.
Guardrails written as bespoke Terraform per constraint do not scale. Each has slightly different handling of inheritance, exceptions and rollout, and nobody can see all of them at once.
And without delivery metrics, a platform team argues about speed from anecdotes. DORA metrics (deployment frequency, lead time, change failure rate and time to restore) are the shared vocabulary, but collecting them requires events from CI, deployment and incident systems in one place.
// The solution
Org policy as a module taking a list. Each element names a constraint, a scope (organisation, folder or project) and a list of rules: allow-all, deny-all, enforce or a specific allowed/denied value list, each with an optional CEL condition. The module iterates the list and creates one policy per element, so adding a control is adding an element.
Conditions make exceptions explicit and reviewable. Instead of disabling a constraint on a project, you add a rule that allows a specific value when a resource tag matches. The exception is a line in the same list, with a comment, in the same pull request flow.
A project factory module creates opinionated projects: billing link, API enablement from a standard list plus extras, shared-VPC service project attachment, standard service accounts and IAM granted to groups rather than individuals. A toggle controls whether roles are inherited from the folder.
In the cluster, Gatekeeper evaluates admission requests against constraint templates written in Rego. One template here forbids external load balancers unless an annotation marks them internal. Four Keys runs as a small pipeline of event collectors that write to BigQuery, from which standard queries compute the four metrics.
- Define policy listconstraint, scope, rules and conditions
- Apply org policyenforce, allow or deny with optional inheritance
- Create projectbilling link, APIs, shared-VPC service project, service accounts
- Bind group rolegroups, not individuals, hold roles
- Admission control gateGatekeeper evaluates load balancer services
- Delivery metricsFour Keys parser feeds BigQuery for DORA
// Before you start
- Terraform 1.5+ with the google provider, and Organization Policy Administrator at the target scope
- A kubernetes cluster you can install Gatekeeper into, with Helm 3
- Basic Rego knowledge (rules, input, violation)
- A BigQuery dataset and permission to create Pub/Sub topics and Cloud Run or Functions for the event collectors
- A CI system and deployment tooling that can emit events with a commit SHA
// Step-by-step implementation
01 Express org policy as a list of constraints
The input is a list of objects. Each has a constraint name, a scope type and ID, an optional
inherit_from_parentflag and a list of rules. Rules are small objects:enforcefor boolean constraints,allow_valuesordeny_valuesfor list constraints,allow_allordeny_all, and an optional CELcondition.Keep the data in a
.tfvars-style file reviewed by a security owner. The module should contain no policy decisions of its own.02 Write the module that turns each element into a policy
Use
google_org_policy_policyand adynamic "rules"block. The parent is built from the scope:organizations/<id>,folders/<id>orprojects/<id>. The policy name is<parent>/policies/<short constraint name>.Rules map directly: booleans use
enforce, lists usevalues { allowed_values / denied_values }, andcondition { expression }carries the CEL. Keepallow_allanddeny_alldistinct so a reviewer never has to infer them.03 Create projects through a factory that pins the baseline
A project module should take a name, a folder and a few options, and hide everything else. It creates the project linked to billing, enables a standard API list plus any extras, attaches the project to a shared VPC host as a service project and creates the standard service accounts.
Grant roles to groups, not people, using additive bindings. An
inherit_rolestoggle controls whether the project also picks up folder-level group roles. Groups come from One Config, Two Clouds: Group and Role Management as Code, so membership is a separate reviewed concern.04 Install Gatekeeper with Helm
Install it with replicas and the audit controller enabled. Admission webhooks are on the critical path of every create, so run at least two replicas and set the failure policy deliberately:
Ignorekeeps the cluster working if Gatekeeper is down,Failis stricter and riskier.Exempt system namespaces from the start; a policy that blocks the control plane is a bad first day.
05 Write the constraint template in Rego
A template defines a new kind and its logic. This one denies a Service of type LoadBalancer unless it carries the cloud provider's internal load balancer annotation. The
violationrule emits a message that tells the developer exactly how to fix the request.Keep the message actionable. A rejection that says only "denied by policy" generates support tickets; one that names the annotation to add does not.
06 Apply the constraint, in audit mode first
A constraint instantiates the template and scopes it. Start with
enforcementAction: dryrunso violations show up in the constraint status without blocking anyone. Review them, fix or exempt, then switch todeny.This staged rollout is the difference between a guardrail people accept and one they route around.
07 Collect delivery events for DORA metrics
Four Keys-style collection needs three event streams: deployments (what SHA reached production and when), changes (commits and their timestamps) and incidents (opened and resolved). Each lands in a raw events table with the source, event type, a JSON payload and a timestamp.
A parser normalises them into
deployments,changesandincidentstables. The raw table is append-only so you can reparse after fixing a bug.08 Compute the four metrics with queries
Deployment frequency is a count per week. Lead time is the median time from commit to deployment of that commit. Change failure rate is the share of deployments linked to an incident, and time to restore is the median incident duration.
Use medians, not means: one stuck change should not dominate a quarter. Define the linking rule (a deployment commit referenced by an incident) in the open so teams cannot argue about the definition afterwards.
// How to verify it works
- Run
terraform planon the org-policy module and confirm one policy per list element, with the correct parent and no unexpected replacements. - Run
gcloud org-policies describe <constraint> --folder=<folder-id> --effectiveand check the effective rules match the config. - Apply a Service of type LoadBalancer without the annotation while the constraint is in
deny: the API must return an error that includes the fix. - With the constraint in dry-run, list
status.violationson it: existing offenders must be listed and still running. - Query
dora.deploymentsafter a test deployment: a row with the commit SHA must appear within the collector's latency.
// Design decisions and trade-offs
- Policy as data: lists, not bespoke code.
- Conditions express exceptions explicitly.
- Groups hold roles; an inheritance toggle controls scope.
// Pitfalls and lessons learned
- Org policy changes can break running workloads on the next update, not immediately. Use dry-run and test at a leaf folder first.
inherit_from_parentinteracts withdeny_allin surprising ways; always check the effective policy, not just the declared one.- A Gatekeeper webhook with fail-closed policy can block the whole cluster if its pods are unavailable. Run replicas and exempt system namespaces.
- Rego typos make a template silently never match. Test templates with
gator verifyor unit tests before applying. - DORA numbers get gamed if the definition is vague. Fix the linking rules in code and publish them.
- Project factories that auto-create default networks undo shared-VPC design. Disable default network creation explicitly.
// Frequently asked questions
How do I manage GCP organization policy with Terraform?
Use google_org_policy_policy with a spec containing rules. Wrap it in a module that iterates a list of constraints so each control is data.
What can I do with a CEL condition in org policy?
Make a rule apply only when a resource tag or attribute matches, so exceptions are explicit and narrow instead of disabling the constraint.
How do I block LoadBalancer Services with Gatekeeper?
Write a ConstraintTemplate whose Rego flags Services of type LoadBalancer lacking the internal annotation, then instantiate it as a constraint, starting in dryrun mode.
What are the four DORA metrics?
Deployment frequency, lead time for changes, change failure rate and time to restore service.
Does Gatekeeper audit existing resources?
Yes. The audit controller periodically evaluates existing objects and records violations in each constraint status.
// The outcome
Baseline controls and DORA metrics applied the same way everywhere.
// Where to take it next
- Add a dashboard on top of the BigQuery views and review the four metrics in a monthly platform review.
- Extend the template library to cover privileged pods, host paths and image registries.
- Feed Gatekeeper audit results into the same alerting as Watching the Watchers: Identity-Tampering Detection with ChatOps Triage.
- Pair this with The GCP Project Factory: Folder, Project, VPC and GKE per Tenant for the full project lifecycle.