Skip to content
Toolkit

Deploying to Google Cloud (staging)

How the staging environment on Google Cloud is built, deployed, rolled back and torn down. What QA sees of it is in staging.md; every API setting it uses is defined in DEPLOYMENT.md.

Shape

PieceWhatDefined in
cardsite-apiCloud Run service, the API image (/server)infra/gcp/modules/cardsite/run.tf
cardsite-webCloud Run service, nginx + the SPA; proxies the API's prefixes to cardsite-api over HTTPS, so the app is same-originapps/web/nginx.conf (header)
cardsite-marketingCloud Run service, nginx + the Astro buildapps/marketing/nginx.conf
cardsite-toolkitCloud Run service, nginx + the toolkit; /config.json written at start, /status/api/{health,ready} proxiedapps/toolkit/docker-entrypoint.sh, infra/nginx/toolkit.conf
cardsite-migrateCloud Run job, the API image's /migrate -dir /migrations upADR-0167
cardsite-seedCloud Run job, seed.sh accounts scripts/staging/seed.shinfra/docker/seed.Dockerfile
Cloud SQL cardsite-stagingPostgreSQL 16, db-f1-micro, daily backups (7 kept), reached only through the Cloud SQL connector (/cloudsql socket)infra/gcp/modules/cardsite/sql.tf
Secret Managerstaging-jwt-secret, staging-database-url, staging-seed-admin-password, staging-seed-qa-password — all generated, none in the repositoryinfra/gcp/modules/cardsite/secrets.tf
UploadsPrivate bucket mounted at /mnt/uploads (UPLOAD_PATH); served by the API at /uploads/…main.tf
Artifact Registry cardsiteImages api, web, marketing, toolkit, seed, tagged with the commit SHA; 20 newest keptmain.tf
Service accountsapi, static (no roles), jobs, deploy — what each may touch is listed at the top of infra/gcp/modules/cardsite/iam.tfiam.tf
Workload Identity FederationPool github-staging; only tokens for aidenlive/Cardsite-GTM are accepted, and only as cardsite-staging-deployiam.tf
OptionalMemorystore Redis (redis_enabled, off: the API runs without it), custom domains (domains, off)redis.tf, run.tf
Optional: TLS edgeOne VM running Caddy with on-demand TLS in front of cardsite-web, for customer domains and the short host (edge_host, public_host; off). See Customer domainsinfra/gcp/modules/cardsite/edge.tf, ADR-0183

Terraform owns configuration; the deploy workflow owns which image runs. Terraform creates every service and job with a placeholder image and then ignores the image (lifecycle.ignore_changes), so terraform apply never rolls back a deploy and a deploy never changes configuration.

The API settings shared by every staging runner (Cloud Run, the Docker parity stack, the native parity run) are one file, infra/staging/api.env: ENV=production, staging rate limits, lifecycle taking off. Each runner adds only its own URLs, DATABASE_URL, JWT_SECRET, TRUSTED_PROXIES and UPLOAD_PATH. No key is new (ADR-0162; npm run check:config-keys).

One-time setup

  1. Project. A GCP project with billing, and an operator with Owner (or the admin roles for Run, SQL, IAM, Secret Manager, Storage, Artifact Registry) for the setup only.

  2. Either Terraform (canonical):

    gcloud auth application-default login
    infra/gcp/bootstrap.sh --project PROJECT_ID --state-bucket-only     # the state's own bucket
    cd infra/gcp/environments/staging
    cp backend.hcl.example backend.hcl && cp terraform.tfvars.example staging.tfvars   # edit both
    terraform init -backend-config=backend.hcl
    terraform apply -var-file=staging.tfvars
    terraform output github_variables
    

    The state holds the generated secrets: keep the bucket private (it is created with public access prevention and versioning).

    Or gcloud only, no Terraform: infra/gcp/bootstrap.sh --project PROJECT_ID creates the same resources under the same names (--dry-run prints every command first). It is idempotent and prints the GitHub variables at the end. It does not add the API's startup and liveness probes (Cloud Run's default TCP probe applies) or the registry cleanup policy. Pick one path per project: Terraform would have to import what the script made.

  3. GitHub variables (Settings → Secrets and variables → Actions → Variables, at repository level or on the staging environment): GCP_PROJECT_ID, GCP_REGION, GCP_WIF_PROVIDER, GCP_DEPLOY_SA, and GCP_AR_REPO if not cardsite. No secrets are stored in GitHub.

  4. First deploy: Actions → Deploy — Staging (GCP) → Run workflow (seed on). Until step 3 is done, every push to main stops at the guard with a notice and succeeds.

Click locations (GeoIP)

Countries, cities and continents come from a MaxMind-format city database (GEOIP_DB_PATH). On GCP it lives in its own private bucket, mounted read-only into the API at /mnt/geoip (infra/gcp/modules/cardsite/geoip.tf):

  1. terraform apply once to create the bucket (output geoip_bucket).
  2. Upload the database: gcloud storage cp dbip-city-lite.mmdb gs://GEOIP_BUCKET/. Staging uses DB-IP Lite City (CC BY 4.0, a monthly public download); production should use MaxMind GeoLite2 City (a free account and key).
  3. geoip_object = "dbip-city-lite.mmdb" in staging.tfvars, then apply. The API gets GEOIP_DB_PATH and 1 GiB of memory.

Clicks recorded before step 3 stay unlocated: the API keeps no address. A visit is located by the address the API believes (ADR-0160, ADR-0183): the edge and web's nginx name the visitor with the edge secret, so both staging.cardsite.io and customer domains locate the visitor, not Google.

Customer domains: the TLS edge

Cloud Run serves only names mapped to it, each verified by the project's owner, so a customer's own domain cannot reach it. The edge is how it does, as Caddy does in production (ADR-0183):

  1. In staging.tfvars: edge_host = "edge.staging.cardsite.io", and optionally public_host = "crd.name" and edge_acme_email. Then terraform apply.
  2. DNS: the A records in terraform output edge_dns_records (each name to edge_ip). No verification step; Caddy issues each certificate once the name resolves.
  3. With public_host: set the GitHub variable STAGING_PUBLIC_HOST to the same value and redeploy, so the web build hands addresses out on it.
  4. A customer adds a domain, points it at edge_host (CNAME; an apex uses an A record to edge_ip) and presses Verify. The first HTTPS request gets a certificate, after the API's /internal/tls/ask says yes.

Check it: curl https://EDGE_HOST/healthz answers ok. The VM's logs: gcloud compute ssh cardsite-staging-edge --zone=us-central1-a --tunnel-through-iap -- journalctl -u caddy -n 100. A changed Caddyfile is applied with terraform output edge_reload_command.

Deploy

.github/workflows/deploy-staging.yml, on every push to main and on demand:

  1. Build and push the five images at ${{ github.sha }} (Buildx, GitHub Actions cache). The toolkit site is built on the runner first (node apps/toolkit/build.mjs; apps/toolkit/Dockerfile says why).
  2. Point both jobs at the new images. With the reset input, wipe the database (seed.sh wipe).
  3. cardsite-migrate runs and is waited on. A failed migration stops the workflow before any service changes: the running revisions keep serving the schema they were built for.
  4. cardsite-seed upserts the two staging accounts (skipped only when run by hand with seed off).
  5. Each service gets a new revision with the new image, api first.
  6. scripts/staging/smoke.sh runs against the four URLs, signing in as qa@cardsite.station.center with the password read from Secret Manager and masked in the log.
  7. The job summary lists the URLs, the image tag and the smoke output.

Deploys never overlap (concurrency: deploy-staging) and an in-flight one is never cancelled.

Migrations policy

The binary never migrates (ADR-0167); the job does, before the services change. So a migration must be safe for the previous revision too: additive, or in two releases (add, deploy, then remove). A rollback rolls back code, never schema. Reverting a migration on staging is a deliberate act: gcloud run jobs execute cardsite-migrate --args=-dir,/migrations,down,1 --wait.

Rollback

gcloud run revisions list --service=cardsite-api --region=REGION      # newest first
gcloud run services update-traffic cardsite-api --region=REGION \
  --to-revisions=cardsite-api-00042-abc=100

Repeat per service that needs it (cardsite-web etc.). A service whose traffic is pinned to a revision does not move to the next deploy's revision; release the pin with gcloud run services update-traffic SERVICE --region=REGION --to-latest once the fix is deployed. Redeploying an older commit is the alternative: run the workflow from that commit's SHA.

Client address

TRUSTED_PROXIES on cardsite-api is 169.254.0.0/16 (variable api_trusted_proxies). The reasoning, in the form of a decision record:

  • Context. The API takes a client address from X-Forwarded-For only when the TCP peer is a proxy the deployment names, and then takes the rightmost entry that is not itself trusted (ADR-0160, ADR-0163; apps/api/internal/middleware/realip.go). On Cloud Run the container's only peer is Cloud Run's own front end, which connects from the link-local range and appends the caller's address to X-Forwarded-For. Nothing outside Google can open a connection from that range to the container.
  • Decision. Trust that range and nothing else. A request straight to the API is then attributed to its caller.
  • Consequence. A request through cardsite-web reaches the API as a new request from the web service's egress address; that address is the rightmost untrusted entry, so every visitor through the web origin shares one rate-limit budget. This is the direction ADR-0160 accepts (throttles too much, never too little), and it is why infra/staging/api.env raises the budgets tenfold. Trusting Google's egress ranges instead would let any Cloud Run tenant forge an address. Per-visitor attribution through the web origin needs nginx and the API in one service (an nginx ingress container with the API as a sidecar on localhost, TRUSTED_PROXIES=127.0.0.1,169.254.0.0/16): the shape to adopt before production.
  • Not yet observed. The peer range and the header Cloud Run passes are taken from Cloud Run's behaviour as documented, not measured here. After the first deploy, sign in once directly against the API URL and check the address recorded for it (the newest users_logs row, or the API log line for the request): it must be your own address, not a 169.254.* or Google one. If it is not, set api_trusted_proxies to what the peer is.

Costs

Estimate at list prices in us-central1, idle-to-light QA use; confirm with the pricing calculator.

ItemMonthly
Cloud SQL db-f1-micro, 10 GB SSD, 7 backups~USD 11–13
Cloud Run, four services and two jobs, scale to zero~USD 0–5 (mostly inside the free tier)
api_min_instances = 1 (no cold starts)+~USD 10
Artifact Registry (≤ 20 versions × 5 images)~USD 1
Secret Manager, Cloud Storage< USD 1
Memorystore BASIC 1 GB (redis_enabled)+~USD 35

Production

Out of scope here. The intended path: a separate project from the same module (environments/production), the production GitHub environment with required reviewers, and a workflow_dispatch that promotes an image SHA already proven on staging (no rebuild). The current .github/workflows/deploy-production.yml deploys over SSH to the host in DEPLOYMENT.md and is unrelated to this environment.

Teardown

cd infra/gcp/environments/staging
terraform apply  -var-file=staging.tfvars -var=db_deletion_protection=false   # lifts the protection
terraform destroy -var-file=staging.tfvars

destroy removes the database and its backups, the uploads bucket and every secret. The Workload Identity pool is soft-deleted for 30 days, during which its id cannot be reused. The state bucket stays (delete it by hand). Without Terraform: delete the services, jobs, SQL instance (after gcloud sql instances patch cardsite-staging --no-deletion-protection), secrets, buckets, service accounts, pool and registry with the matching gcloud … delete commands.

Local parity

The same images and topology without GCP:

Command
Dockernode apps/toolkit/build.mjs, then STAGING_JWT_SECRET=$(openssl rand -hex 32) docker compose -f infra/compose.staging.yml up -d --build --wait
No Dockerscripts/staging/local-native.sh up (and down)

Both serve web :18080, API :18081, marketing :18082, toolkit :18083, run migrate and seed as one-shot steps, and end with smoke.sh. They seed the development accounts too, and use the local-only password demo-placeholder-password for the two staging accounts.

Source: docs/guides/deploy-gcp.md

Library