Security & FinOps · Governance

Guardrails and Engineering Telemetry: Org Policy, Project Factory, Gatekeeper, Four Keys

Reusable GCP governance modules, cluster-level admission policy and DORA metrics.

  • Terraform
  • GCP Org Policy
  • OPA Gatekeeper
  • Rego
  • Helm
  • BigQuery

// 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.

How it flows flow1. Define policy list → 2. Apply org policy → 3. Create project → 4. Bind group role → 5. Admission control → 6. Delivery metrics01Define policy list02Apply org policy03Create project04Bind group role05 · GATEAdmission control06Delivery metrics
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Define policy listconstraint, scope, rules and conditions
  2. Apply org policyenforce, allow or deny with optional inheritance
  3. Create projectbilling link, APIs, shared-VPC service project, service accounts
  4. Bind group rolegroups, not individuals, hold roles
  5. Admission control gateGatekeeper evaluates load balancer services
  6. Delivery metricsFour Keys parser feeds BigQuery for DORA
Organisationorg policy listCEL conditionsfolder scopeProjectproject factoryshared VPCgroup IAMClusterGatekeeper templatesconstraintsauditTelemetryFour Keys collectorsBigQueryDORA queries
Three control planes, one baseline. Cloud-level policy, cluster-level admission and delivery telemetry.
DeveloperAPI serverGatekeeperkubectl apply Service type LoadBalancerAdmissionReview requestRego checked: internal annotation present?Deny with message, or allowError explaining how to request an internal LB
Admission decision for a LoadBalancer Service. The API server asks Gatekeeper before persisting the object.

// 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

  1. 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_parent flag and a list of rules. Rules are small objects: enforce for boolean constraints, allow_values or deny_values for list constraints, allow_all or deny_all, and an optional CEL condition.

    Keep the data in a .tfvars-style file reviewed by a security owner. The module should contain no policy decisions of its own.

  2. 02 Write the module that turns each element into a policy

    Use google_org_policy_policy and a dynamic "rules" block. The parent is built from the scope: organizations/<id>, folders/<id> or projects/<id>. The policy name is <parent>/policies/<short constraint name>.

    Rules map directly: booleans use enforce, lists use values { allowed_values / denied_values }, and condition { expression } carries the CEL. Keep allow_all and deny_all distinct so a reviewer never has to infer them.

  3. 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_roles toggle 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.

  4. 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: Ignore keeps the cluster working if Gatekeeper is down, Fail is stricter and riskier.

    Exempt system namespaces from the start; a policy that blocks the control plane is a bad first day.

  5. 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 violation rule 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.

  6. 06 Apply the constraint, in audit mode first

    A constraint instantiates the template and scopes it. Start with enforcementAction: dryrun so violations show up in the constraint status without blocking anyone. Review them, fix or exempt, then switch to deny.

    This staged rollout is the difference between a guardrail people accept and one they route around.

  7. 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, changes and incidents tables. The raw table is append-only so you can reparse after fixing a bug.

  8. 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 plan on 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> --effective and 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.violations on it: existing offenders must be listed and still running.
  • Query dora.deployments after 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_parent interacts with deny_all in 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 verify or 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

// Keep reading