← Back to Articles
Architecture 20 min read

A GCP Sandbox That Can't Surprise You

One billing account, a dedicated project per demo, and four layers of cost guardrails, built and tested with real code and the console, so learning Google Cloud never ends in a surprise bill.

I wanted one Google Cloud account to be my sandbox for everything I learn: every demo, every experiment, every "what happens if I click this" for months to come. Spin up a demo, break things, delete it, start the next one. The only rule was no surprise bills, so I drew a line at $15 a month across everything.

The point of the setup below is that I build the safety once, and every future demo inherits it with one command. I don't want to think about cost each time I try something new; I want a sandbox where the worst case is known before I start.

It turned out that the obvious tool, a budget, does not do what most people think. This is how I set up the account instead, with the real code, the console path for every step, and the mistakes I hit on the way. I built it with Claude Code: I set the limits and reviewed every change as a pull request, Claude Code wrote the scripts and ran most of them, and I ran the steps that grant permissions or delete projects myself.

This is part 1 of a series. Part 2 uses this sandbox to practice CI/CD on Cloud Run.

What "safe" means here

A budget in Google Cloud sends emails. It does not stop anything. Google's own docs say it directly: budgets do not cap usage. So a safe account needs more than one layer, each covering what the others can't:

  • Layer 1, an account-wide budget: emails you at $7.50, $13.50 and $15, across every project. It tells you; it doesn't act.
  • Layer 2, a backstop: a small function that reads budget messages and disconnects billing from a project that went over. It acts on every service, but it's blunt.
  • Layer 3, spend caps: Google itself pauses one service in one project at a limit. Precise, but only for a few services.
  • Layer 4, quotas: hard limits that apply the moment you set them, such as how much BigQuery may scan per day. They cover the hours before cost data arrives.
Four stacked layers: account budget (alerts), backstop (disconnects billing), spend caps (pause one service), quotas (immediate limits), with an arrow showing each one covers a gap in the one above
Four layers, each covering what the others can't

Step 0: check where your account really stands

New accounts get a free trial: $300 of credit over 90 days, and Google won't charge you unless you upgrade by hand. That is the one setup that truly can't bill you.

The catch I didn't know: the 90 days start when you sign up, not when you start using it. I had signed up years ago, never used the credit, and it was gone.

Google Cloud billing overview with a banner saying the free trial is over and the cost summary at zero
The trial clock had run out years earlier, unused

Console: Billing, then Overview. A credit card with an end date means the trial is active. A "free trial is over" banner means you upgrade to a paid account (the Upgrade button). Upgrading charges nothing by itself.

Code: the CLI shows whether the billing account is open, but not trial status or payment methods (those only appear in the console):

gcloud billing accounts list

Two things surprised me on the payment page. First, the account had no card on file, even after upgrading; add one before running anything. Second, there is a Prepay option that sounds safer, but it only covers the Gemini API in AI Studio, not Cloud Run, BigQuery or storage. Everything here runs on Postpay: you pay after the month, for what you used.

Billing payment page showing Paid account, a red "Set a primary payment method" banner, a zero balance and the Postpay plan
Upgraded, but no card yet: the red banner says so

One billing account, one project per demo

Two words that are easy to mix up:

  • A billing account is who pays: the card, the invoices, the budgets. One can pay for many projects.
  • A project is where things live: services, buckets, datasets.

So the design is one general billing account that is the sandbox for all my learning, and a new project for every demo inside it. The guardrails sit at two levels: some on the billing account, protecting everything at once, and some added to each project as it's created. A new demo never starts unprotected, because the only way I create one is the script that adds its guardrails. Deleting a project ends all of its costs at once, and cost reports split cleanly by project. One thing to know: the free tier is counted per billing account, so all your demos share it.

Before building anything, I unlinked billing from the old "My First Project" Google had created at signup. It was empty, but a project that can bill and that you don't use is a gap.

Console: Billing, Account management, the Your projects tab, the three dots on the row, Disable billing.

Code:

gcloud billing projects unlink OLD_PROJECT_ID

All the code below lives in one small repo with a shared settings file. Every value specific to my account sits here, so the scripts themselves stay generic:

# config.sh: shared settings, sourced by every script
          BILLING_ACCOUNT="XXXXXX-XXXXXX-XXXXXX"   # your billing account ID
          GUARD_PROJECT="billing-guard-abc123"     # project IDs are unique across all of Google
          REGION="us-central1"                     # free tier regions are US only
          ACCOUNT_BUDGET="15USD"                   # must match the account's currency
          BACKSTOP_DRY_RUN="false"                 # "true": the backstop only logs

Amounts in this article are in US dollars. A budget's currency must match the billing account's, and mine actually bills in shekels, so my own files say ILS. Use your account's currency code.

Layer 1: an account-wide budget

First, a lesson the console hides. A budget belongs to the billing account, not a project, but every API call has to be counted against some project, called the quota project. With no billable project yet, there's nowhere to count it. So the first script creates a small guardrails project, which later also hosts the backstop:

gcloud projects create "$GUARD_PROJECT" --name="billing-guardrails"
          gcloud billing projects link "$GUARD_PROJECT" --billing-account="$BILLING_ACCOUNT"
          gcloud services enable billingbudgets.googleapis.com --project="$GUARD_PROJECT"

Creating a project, linking billing and enabling an API are all free. When I listed the project's APIs afterwards, about 24 were on, not one: Google enables a default set (BigQuery, Storage, Logging and more) on every new project. Enabled doesn't mean costing. An API is a door, not a meter; you pay only when something goes through it.

Then the budget itself:

gcloud billing budgets create \
            --billing-account="$BILLING_ACCOUNT" \
            --billing-project="$GUARD_PROJECT" \
            --display-name="account-total" \
            --budget-amount="$ACCOUNT_BUDGET" \
            --threshold-rule=percent=0.5 \
            --threshold-rule=percent=0.9 \
            --threshold-rule=percent=1.0 \
            --threshold-rule=percent=1.0,basis=forecasted-spend

Line by line:

  • --billing-account with no project or service filter: the budget watches everything on the account.
  • --billing-project: the quota project from above. In the console you never see this.
  • --budget-amount=15USD: the currency has to match the account's.
  • Three percent rules: emails at $7.50, $13.50 and $15 of actual spend.
  • basis=forecasted-spend: an early email if Google predicts you'll reach $15 this month.

Console: Billing, Budgets & alerts, Create budget. Scope: all projects, all services. Amount: $15. Actions: add the four thresholds (three Actual, one Forecasted), and keep email alerts on.

On the budget's edit page you'll see a second option, Spend cap enforcement, greyed out. That isn't a bug; it's Layer 3's rules, below.

Edit budget page with "Alerts only" selected and "Spend cap enforcement (available for limited services)" greyed out, scope set to all projects and all 1,779 services
An account-wide budget can only be alerts

Layer 2: a backstop that disconnects billing

Why build one at all

Layer 1 only tells me. That's fine when I'm at my desk, but the whole idea of a sandbox is that I'll leave demos running, forget about them, or make a mistake at night. An email at 2am doesn't stop a query in a loop. I needed something that acts on its own, for any service, without me in the loop.

The other options don't cover that:

  • Spend caps (Layer 3) act on their own, but only for a few services. Nothing caps BigQuery, Cloud Storage or Firestore.
  • Quotas (Layer 4) are immediate, but they limit specific things, not money.
  • Watching the bill myself fails exactly when it matters, when I'm not watching.

The backstop is the one piece that turns "I got an email" into "it stopped". It's blunt on purpose: when a demo goes over its budget, billing is disconnected from that project and everything in it stops. For a learning sandbox that's the right trade. Losing a demo is cheap; an open-ended bill isn't.

How it works

Google documents a pattern for a real stop: a function that disconnects billing when a budget is exceeded. Budgets can't run code, but they can publish a message to Pub/Sub, and a function can listen.

Flow from a budget publishing "cost $X of $Y" to the Pub/Sub topic budget-alerts, through an Eventarc trigger, to the billing-backstop function, which calls the Cloud Billing API to unlink the over-budget project
Budget, topic, function, disconnect

The decision logic

All the decisions live in one small Python file. The message Google sends looks like this (simplified):

{"budgetDisplayName": "account-total", "costAmount": 4.10, "budgetAmount": 15.0, "currencyCode": "USD"}

And the function:

BILLING_ACCOUNT = os.environ["BILLING_ACCOUNT"]
          GUARD_PROJECT = os.environ["GUARD_PROJECT"]
          # Safe by default: anything other than "false" only logs what it would do.
          DRY_RUN = os.environ.get("DRY_RUN", "true").lower() != "false"

          ACCOUNT_BUDGET = "account-total"
          PROJECT_BUDGET_PREFIX = "project:"

          # force: functions-framework sets up logging before this runs, which would drop INFO lines.
          logging.basicConfig(level=logging.INFO, force=True)
          client = billing_v1.CloudBillingClient()


          @functions_framework.cloud_event
          def handle(event):
              msg = json.loads(base64.b64decode(event.data["message"]["data"]))
              name = msg["budgetDisplayName"]
              cost, budget = msg["costAmount"], msg["budgetAmount"]
              currency = msg.get("currencyCode", "")

              if cost < budget:
                  logging.info("%s: %.2f of %.2f %s, under budget, no action", name, cost, budget, currency)
                  return

              if name == ACCOUNT_BUDGET:
                  targets = linked_projects()
              elif name.startswith(PROJECT_BUDGET_PREFIX):
                  targets = [name.removeprefix(PROJECT_BUDGET_PREFIX)]
              else:
                  logging.warning("%s: over budget but the name matches no rule, no action", name)
                  return

              for project in targets:
                  if project == GUARD_PROJECT:
                      continue  # keep the guardrails running
                  disconnect(project, f"{name}: {cost:.2f} of {budget:.2f} {currency}")


          def linked_projects():
              """Project IDs currently billed to the billing account."""
              infos = client.list_project_billing_info(name=f"billingAccounts/{BILLING_ACCOUNT}")
              return [i.project_id for i in infos if i.billing_enabled]


          def disconnect(project, reason):
              if DRY_RUN:
                  logging.warning("DRY_RUN: would disconnect billing from %s (%s)", project, reason)
                  return
              # An empty billing account name is how the API says "unlink billing".
              client.update_project_billing_info(
                  name=f"projects/{project}",
                  project_billing_info=billing_v1.ProjectBillingInfo(billing_account_name=""),
              )
              logging.warning("Disconnected billing from %s (%s)", project, reason)

The parts worth reading slowly:

  • DRY_RUN is safe by default. Only the exact word false makes it act. A typo or an empty value keeps it logging, so a mistake in the setting can only make it safer.
  • @functions_framework.cloud_event marks handle as the entry point. Pub/Sub wraps the message in base64 so it can carry any bytes; the first line unwraps it.
  • Rule 1: under budget, stop. Budgets publish several times a day even at $0, so this is what nearly every run does. The function compares the numbers itself rather than trusting a threshold field.
  • Rule 2: the budget's name picks the target. account-total means every project on the account; project:<id> means only that one. A name that matches nothing never acts, which is the safe default.
  • Rule 3: never cut the guardrails project, so the protection survives its own action.
  • Rule 4: disconnecting is setting the project's billing account to an empty string.

Wiring it up

The setup script creates the pipes around that code: the Pub/Sub topic, two service accounts with only the rights they need, the deploy, and the connection from the budget to the topic. The deploy is the interesting part:

gcloud functions deploy billing-backstop \
            --gen2 --runtime=python312 --region="$REGION" --project="$GUARD_PROJECT" \
            --source="functions/backstop" --entry-point=handle \
            --trigger-topic="budget-alerts" \
            --service-account="$SA" --trigger-service-account="$SA" \
            --build-service-account="projects/$GUARD_PROJECT/serviceAccounts/$BUILDER" \
            --memory=256Mi --max-instances=1 --ingress-settings=internal-only \
            --set-env-vars="BILLING_ACCOUNT=$BILLING_ACCOUNT,GUARD_PROJECT=$GUARD_PROJECT,DRY_RUN=$BACKSTOP_DRY_RUN"
  • What to run: this folder, Python 3.12, start at handle().
  • How it's triggered: every message on the budget-alerts topic.
  • Who it runs as: its own service account. That account can see which projects use billing (Billing Account Viewer) but can only disconnect projects where it was given Project Billing Manager, one project at a time.
  • How big: 256 MiB and at most one instance, so the safety net can never become a cost.
  • Who can reach it: internal-only, explained below.
  • Settings: environment variables, not code, so switching dry run off is a setting change.

Under the hood, a "Cloud Run function" is a Cloud Run service where Google writes the Dockerfile: the source is zipped, Cloud Build turns it into an image, Artifact Registry stores it, and Cloud Run serves it as a revision. That made the backstop a nice first look at Cloud Run.

Connecting the budget is one more command:

gcloud billing budgets update "$BUDGET" \
            --billing-account="$BILLING_ACCOUNT" --billing-project="$GUARD_PROJECT" \
            --notifications-rule-pubsub-topic="projects/$GUARD_PROJECT/topics/budget-alerts"

Console: Pub/Sub, Topics, Create topic. Then Cloud Run functions, Create function, with a Pub/Sub trigger on that topic, Python 3.12, and the code pasted in. Then the budget's Manage notifications, "Connect a Pub/Sub topic". It works, but this is where the script pays off: about a dozen settings across four products, every one of which has to be right.

Ingress: two locks on one door

After the first deploy the function had a public URL. An anonymous call got 403 Forbidden, so identity (IAM) was already protecting it. I still set ingress to internal:

  • Ingress answers "where may requests come from?" IAM answers "who are you, and are you allowed?"
  • With ingress open, a stranger's request reaches the door and IAM turns it away. With internal ingress, Google drops it before it arrives.
  • The real reason is mistakes, not attackers. If anyone ever adds --allow-unauthenticated (a flag in many Cloud Run tutorials), an open ingress would let anyone send a fake "over budget" message and switch off my demos. Internal ingress means one mistake isn't enough.
  • Pub/Sub still gets through, because Google counts it as internal traffic.

Console: Cloud Run, the service, the Networking tab, Ingress: Internal. Leave "Allow traffic from external application load balancers" unchecked. Then "View diff and redeploy" at the top right.

Cloud Run Networking tab with Ingress set to Internal and the external load balancer box unchecked
Ingress is a service setting: it decides who can reach the door

The console then offers "Force a revision to be deployed". Leave it unchecked: ingress belongs to the service (the front door), not to a revision (the code inside). In my case the console created an identical revision anyway; both revisions pointed to the same image fingerprint, which is how I could tell.

Testing it without risk

With DRY_RUN=true, I published two fake messages, one under budget and one over budget for a made-up project:

gcloud pubsub topics publish budget-alerts --project="$GUARD_PROJECT" \
            --message='{"budgetDisplayName":"project:fake-demo-project","costAmount":6.0,"budgetAmount":5.0,"currencyCode":"USD"}'

The logs showed DRY_RUN: would disconnect billing from fake-demo-project. The under-budget message ran fine (HTTP 200) but left no log line. The cause: Google's Python framework sets up logging before your code runs, so a plain logging.basicConfig(level=INFO) does nothing and INFO lines are dropped. Adding force=True fixed it. It's a one-word bug that would have hidden every routine message.

A small bonus: a few minutes later a message arrived that I hadn't sent. It was a real budget notification from Google, proving the whole chain end to end.

Layer 3: spend caps, powerful but narrow

Spend caps are newer: when a project's spend on a service reaches the cap, Google pauses new usage of that service until the next month or until you lift it. Nothing is deleted. The rules are strict:

  • One project and one service per cap. That's why the account-wide budget can only be alerts.
  • Only a few services: Cloud Run, Cloud Run functions, the Gemini API and Vertex AI.
  • It isn't instant, and usage before it triggers is billed normally.

There's no gcloud command for spend caps yet, so the script calls the Budget API directly:

curl -sS --fail-with-body -X POST \
            -H "Authorization: Bearer $TOKEN" -H "x-goog-user-project: $GUARD_PROJECT" \
            -H "Content-Type: application/json" \
            "https://billingbudgets.googleapis.com/v1/billingAccounts/$BILLING_ACCOUNT/budgets" \
            -d @- <<EOF
          {
            "displayName": "cap:$PROJECT_ID:cloud-run",
            "budgetFilter": {
              "projects": ["projects/$PROJECT_ID"],
              "services": ["services/152E-C115-5142"],
              "creditTypesTreatment": "EXCLUDE_ALL_CREDITS",
              "calendarPeriod": "MONTH"
            },
            "amount": {"specifiedAmount": {"currencyCode": "USD", "units": "$CAP_USD"}},
            "thresholdRules": [{"thresholdPercent": 0.5}, {"thresholdPercent": 0.8}, {"thresholdPercent": 1.0}],
            "notificationsRule": {"enableProjectLevelRecipients": true},
            "spendCap": {"inputState": "CONFIGURED"}
          }
          EOF
  • 152E-C115-5142 is Cloud Run's billing service ID, from Google's list of eligible services.
  • x-goog-user-project is the quota project again, as a header this time.
  • spendCap.inputState: CONFIGURED is what turns an alert budget into a cap.

My first two attempts failed, and both errors taught something:

  • "Spend Cap cannot select credits." Budgets subtract credits by default; spend caps only work on gross cost. The free tier counts as a credit, so a spend cap counts free-tier usage too. A demo with a $0 bill but $3 of free Cloud Run usage would hit a $2 cap. Size caps to expected usage, not to the expected bill.
  • "Spend Caps must have exactly three thresholds: 50%, 80%, and 100%." No other set is accepted.

Console: Budgets & alerts, Create budget, choose "Spend cap enforcement", then one project and one eligible service.

Layer 4: quotas, starting with BigQuery

BigQuery on-demand charges by data scanned, and the default daily query quota per project is 200 TiB. On a learning account, a query in a loop could cost far more than any budget before the cost data even arrives. And BigQuery is enabled by default in every new project, so this applies whether you use it or not.

Quotas take effect within minutes, which makes them the one layer that works before the billing data catches up. The gcloud quota commands are in the beta component, so the script uses the Cloud Quotas API:

curl -sS --fail-with-body -X POST \
            -H "Authorization: Bearer $TOKEN" -H "x-goog-user-project: $PROJECT_ID" \
            -H "Content-Type: application/json" \
            "https://cloudquotas.googleapis.com/v1/projects/$PROJECT_ID/locations/global/quotaPreferences?quotaPreferenceId=bq-query-per-day&ignoreSafetyChecks=QUOTA_DECREASE_PERCENTAGE_TOO_HIGH" \
            -d "{\"service\": \"bigquery.googleapis.com\", \"quotaId\": \"QueryUsagePerDay\",
                 \"quotaConfig\": {\"preferredValue\": \"$((BQ_DAILY_GIB * 1024))\"}, \"dimensions\": {}}"
  • The unit is MiB. The error message confirmed it: the current limit read 209715200, which is exactly 200 TiB in MiB, so 1024 means 1 GiB a day.
  • Google refuses cuts of more than 10% unless you say it's intentional. That's a guardrail for production systems, and ours is a 99.99% cut. Setting ignoreSafetyChecks to QUOTA_DECREASE_PERCENTAGE_TOO_HIGH skips that one check and nothing else.
  • It's a URL parameter, not a body field. I put it in the JSON first and got "Unknown name ignoreSafetyChecks". The API reference lists it under query parameters.
  • It can fail right after the project is created. On my second demo project this call returned 403 Permission 'cloudquotas.quotas.update' denied, although I'm the project's Owner. The script had turned on the Cloud Quotas API a few seconds earlier, and a newly enabled API takes a minute or two to reach all of Google's servers. The same call worked a minute later, so the script now retries it up to 5 times, 20 seconds apart.

The response came back with "preferredValue": "1024", "grantedValue": "1024": asked for and granted.

Console: IAM & Admin, Quotas & System Limits, filter for "Query usage per day", select it, Edit, enter the new value.

One command per demo

All of this per-project setup lives in one script. Each demo gets a small settings file:

# projects/my-demo.env
          NAME="my-demo"                 # also the gcloud configuration name
          PROJECT_ID="my-demo-abc123"    # unique across all of Google
          BUDGET_USD=5                   # the backstop disconnects at this amount
          CAP_USD=5                      # Cloud Run spend cap, gross cost incl. free tier
          BQ_DAILY_GIB=10                # BigQuery: max GiB queried per day
          APIS="run.googleapis.com"      # only what this demo needs

Then ./new-project.sh projects/my-demo.env runs eight blocks: create the project with a managed-by label, link billing, enable only the listed APIs, create the project:<id> budget connected to the backstop, create the Cloud Run spend cap, give the backstop Project Billing Manager on this project only, lower the BigQuery quota, and create a named gcloud configuration.

That last one is underrated. A gcloud configuration is a saved set of settings, so gcloud config configurations activate my-demo switches project, account and region together, and a command can't land in the wrong project by accident.

./teardown-project.sh projects/my-demo.env reverses it: it deletes the budgets first (they belong to the billing account and would outlive the project), then the project, which Google keeps for 30 days before deleting for good, then the configuration.

Proving the backstop really works

A safety net you've never tested is a guess. So I created a throwaway project with the script, switched the backstop from dry run to real, and sent it a fake "$3 of $2" message:

gcloud pubsub topics publish budget-alerts --project="$GUARD_PROJECT" \
            --message='{"budgetDisplayName":"project:backstop-test-abc123","costAmount":3.0,"budgetAmount":2.0,"currencyCode":"USD"}'

Before: billingEnabled=True. Within seconds the log said Disconnected billing from backstop-test-abc123, and after: billingEnabled=False. The cost was fake; the disconnect was real. Then the teardown script removed the project and its budgets.

What it costs, and what it can't do

So far it has cost $0. The backstop runs a few times a day, far inside the free tiers of Pub/Sub, Cloud Run and Cloud Build.

What it can't do, plainly:

  • It isn't instant. Cost data runs a few hours behind, and usage in that gap is billed. Quotas and max-instances keep the gap small.
  • It's an emergency brake. Disconnecting billing stops everything in the project, and resources may be deleted if billing stays off. For demos, that's a fair trade.
  • It only protects projects made with the script, because only those give the backstop permission. A project created by hand in the console isn't covered.
  • Worst case is the cap plus whatever accumulates during the delay.

Making it repeatable: a Claude Code skill

Scripts make each step repeatable. But the setup is more than scripts: the order of the steps, what to check after each one, which steps a person should run, and the errors you'll hit on the way. That knowledge was spread across a long session. So I packaged it as a Claude Code skill, gcp-sandbox. You can download it at the end of this section.

It has four modes:

  • Set up the sandbox: once per billing account. It checks the account, fills in the settings, builds the guardrails project, the budget and the backstop, tests the backstop in dry run, and proves the real stop on a throwaway project before arming it.
  • New demo project: asks for the budget, the Cloud Run cap and the APIs, writes the settings file, runs the script, then verifies every guardrail with read-only checks.
  • Tear down: budgets first, then the project and its configuration.
  • Health check: read-only. Is the backstop armed, are real budget messages arriving, and is any billed project missing its guardrails?

The skill also carries its working rules, the same ones I followed here: explain every command before running it, wait for a yes, and leave the steps that grant permissions or delete projects to the person. Alongside it sits a lessons file with every error from this article and what each one means, so the next setup starts where this one ended. Starting a new demo is now one request: "set up a new demo project for X".

Get the skill. The zip holds SKILL.md, the lessons file and the script templates, with placeholders instead of any real IDs. To install it, unzip it into ~/.claude/skills/, so you get ~/.claude/skills/gcp-sandbox/SKILL.md, then start Claude Code and ask it to set up a GCP sandbox.

Download gcp-sandbox.zip (17 KB)

Read SKILL.md here
---
name: gcp-sandbox
description: Set up and run a cost-guarded Google Cloud sandbox for learning and demos. Covers the one-time account setup (billing and free-trial check, account-wide budget, a billing backstop function that disconnects over-budget projects), creating each new demo project with its own budget, Cloud Run spend cap, BigQuery query quota and gcloud configuration, testing the backstop, health checks, and tearing a demo project down. Use when the user wants to start learning GCP without surprise bills, create or delete a GCP demo project with cost limits, or check that their GCP cost guardrails still work.
---

# GCP sandbox: one billing account, many demo projects, no surprise bills

A learning sandbox on Google Cloud: one billing account that pays for everything, a dedicated project per
demo, and four layers of cost guardrails built once and inherited by every new demo.

- **Layer 1, account budget:** emails at 50/90/100% of a monthly limit across every project. Alerts only.
- **Layer 2, backstop:** budget -> Pub/Sub -> a Cloud Run function that disconnects billing from a project
  that went over its budget. Acts on every service; blunt on purpose.
- **Layer 3, spend caps:** Google pauses Cloud Run in one project at a cap. Precise, few services only.
- **Layer 4, quotas:** BigQuery bytes queried per day (default 200 TiB). Takes effect within minutes.

The scripts in `templates/` are proven end to end. `reference/lessons.md` holds every error hit while
building them and what each one means; read it before changing any script.

## Working rules (always)

1. **Explain before running.** For every command that changes GCP or GitHub: say what it does, why, what it
   costs, and how to undo it, then wait for the user's go. Read-only checks (`list`, `describe`, logs) need
   no approval.
2. **The user runs permission grants and deletions.** Claude Code's auto mode blocks IAM grants (block 6 of
   `new-project.sh`) and project deletion. Hand those commands to the user with the expected output.
3. **Nothing is created by hand in the console.** The console is for looking. Changes go through the
   scripts, so the repo stays the record. If the user wants to learn the console path, show it, then check
   for drift afterwards.
4. **One change per PR** in the sandbox repo, when it is a git repo with the usual branch-and-PR rule.
5. **Never put** the billing account ID, project IDs or the user's email into anything meant for sharing.

## Find out where the user is

- No sandbox repo yet (no `config.sh` with a real `BILLING_ACCOUNT`) -> **Mode A**.
- Sandbox repo exists, the user wants a new demo -> **Mode B**.
- The user is done with a demo -> **Mode C**.
- "Is it still working?", or before a risky demo -> **Mode D**.

## Mode A: set up the sandbox (once per billing account)

1. **Check the account (read-only):** `gcloud billing accounts list`, then `gcloud billing projects list
   --billing-account=<id>`. Payment methods and trial status are console-only: ask for a screenshot of
   Billing > Overview and Billing > How you pay. Key facts: the 90-day trial clock starts at signup, not
   first use; "Upgrade" alone charges nothing; a card must be on file before step 5; Prepay only covers
   the Gemini API in AI Studio, so everything here is Postpay.
2. **Unlink unused billed projects** (user's choice): `gcloud billing projects unlink <project>`.
3. **Create the repo** from `templates/` (all files, including `CLAUDE.md`). Fill `config.sh`: billing
   account ID, currency (`gcloud billing accounts describe <id>`; budgets must use it), a random 6-char
   suffix for `GUARD_PROJECT`, the account limit. Keep `BACKSTOP_DRY_RUN="true"`.
4. **`account/01-guardrails-project.sh`:** guardrails project, billing link, Budgets API. Explain the quota
   project: budget API calls must be counted against some project, and this is it. Expect ~24 APIs to be
   on afterwards (Google's default set); enabled is not costing.
5. **`account/02-account-budget.sh`:** the account budget. Point out it only sends emails, and that the
   console's "Spend cap enforcement" option is greyed out for an all-projects budget by design.
6. **`account/03-backstop.sh`:** topic, two service accounts, deploy in dry run (internal-only ingress,
   max 1 instance), connect the account budget to the topic. First deploy takes a few minutes.
7. **`account/04-test-backstop.sh`** (dry run only): expect "under budget, no action" and "DRY_RUN: would
   disconnect billing from fake-demo-project" in the logs within a minute or two.
8. **Prove the stop, then arm it:** create a throwaway project with Mode B (small budget), set
   `BACKSTOP_DRY_RUN="false"` in `config.sh`, run `account/deploy-backstop.sh`, then publish a fake
   over-budget message for `project:<throwaway-id>` and confirm `billingEnabled` turns `False`. Then Mode C
   on the throwaway project. Don't run `04-test-backstop.sh` once armed (it targets a made-up project).

## Mode B: a new demo project

1. **Write `projects/<name>.env`** from `projects/example.env`. Ask the user for: the budget (the backstop
   disconnects at it), the Cloud Run cap (counts **gross** cost including free-tier usage, so size it to
   expected usage, not the expected bill), BigQuery GiB per day, and the APIs the demo needs (only those).
   Generate a random 6-char suffix for `PROJECT_ID`.
2. **Run `./new-project.sh projects/<name>.env`.** If auto mode blocks it (block 6 grants IAM), the user
   runs it. If a block fails, the script stops there: fix the cause, then run only the remaining blocks:
   `{ sed -n '1,/^TOKEN=/p' new-project.sh; sed -n '/^# N\./,$p' new-project.sh; } | bash -s projects/<name>.env`
   (replace N with the first block to run). Never rerun the whole script: block 1 fails on an existing
   project.
3. **Verify (read-only):**
   - `gcloud billing budgets list --billing-account=<id> --billing-project=<guard> --filter="displayName:<project-id>"`:
     `project:<id>` connected to `budget-alerts`, and `cap:<id>:cloud-run` with `spendCap.outputState: CONFIGURED`
   - `gcloud projects get-iam-policy <project-id> --flatten="bindings[].members" --filter="bindings.members:billing-backstop"`:
     `roles/billing.projectManager`
   - the quota response showed `grantedValue` equal to `preferredValue`
4. Tell the user to switch with `gcloud config configurations activate <name>`.

## Mode C: tear a demo down

The user runs `./teardown-project.sh projects/<name>.env`: deletes the project's budgets (they belong to the
billing account and would outlive the project), shuts the project down (restorable for 30 days with
`gcloud projects undelete`), deletes the gcloud configuration. A spend cap budget can't be deleted while
its cap is enforced: lift it in the console first. Then verify read-only: the project is
`DELETE_REQUESTED`, its budgets are gone, it's not in `gcloud billing projects list`.

## Mode D: health check (read-only)

- `gcloud billing budgets list ...`: the account budget is connected to the topic; each project budget too.
- `gcloud run services describe billing-backstop --region=<region> --project=<guard>`: `DRY_RUN` value,
  ingress `internal`.
- `gcloud functions logs read billing-backstop --gen2 --region=<region> --project=<guard> --limit=20`:
  real budget messages arrive several times a day ("under budget, no action").
- `gcloud billing projects list --billing-account=<id>`: every billed project should be the guard project
  or one made by `new-project.sh` (label `managed-by=gcp-playground`). A project created by hand is not
  protected by the backstop: flag it.

## What it can't do (say this plainly when relevant)

Cost data runs a few hours behind, and usage in that gap is billed. Disconnecting billing stops everything
in the project and resources may be deleted if billing stays off. Only projects made with
`new-project.sh` give the backstop permission. Worst case: the limit plus what accumulates in the delay.

The takeaway

A budget is a smoke alarm, not a sprinkler. If you want a learning account that can't surprise you, put the stop where the action is: a backstop that disconnects billing, spend caps where Google offers them, and quotas for anything that can scan or scale, then prove the stop works on a project you don't care about.

Next in the series: using this sandbox to practice CI/CD on Cloud Run, from a manual deploy to GitHub Actions without any stored keys.

Further reading