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
| Piece | What | Defined in |
|---|---|---|
cardsite-api | Cloud Run service, the API image (/server) | infra/gcp/modules/cardsite/run.tf |
cardsite-web | Cloud Run service, nginx + the SPA; proxies the API's prefixes to cardsite-api over HTTPS, so the app is same-origin | apps/web/nginx.conf (header) |
cardsite-marketing | Cloud Run service, nginx + the Astro build | apps/marketing/nginx.conf |
cardsite-toolkit | Cloud Run service, nginx + the toolkit; /config.json written at start, /status/api/{health,ready} proxied | apps/toolkit/docker-entrypoint.sh, infra/nginx/toolkit.conf |
cardsite-migrate | Cloud Run job, the API image's /migrate -dir /migrations up | ADR-0167 |
cardsite-seed | Cloud Run job, seed.sh accounts scripts/staging/seed.sh | infra/docker/seed.Dockerfile |
Cloud SQL cardsite-staging | PostgreSQL 16, db-f1-micro, daily backups (7 kept), reached only through the Cloud SQL connector (/cloudsql socket) | infra/gcp/modules/cardsite/sql.tf |
| Secret Manager | staging-jwt-secret, staging-database-url, staging-seed-admin-password, staging-seed-qa-password — all generated, none in the repository | infra/gcp/modules/cardsite/secrets.tf |
| Uploads | Private bucket mounted at /mnt/uploads (UPLOAD_PATH); served by the API at /uploads/… | main.tf |
Artifact Registry cardsite | Images api, web, marketing, toolkit, seed, tagged with the commit SHA; 20 newest kept | main.tf |
| Service accounts | api, static (no roles), jobs, deploy — what each may touch is listed at the top of infra/gcp/modules/cardsite/iam.tf | iam.tf |
| Workload Identity Federation | Pool github-staging; only tokens for aidenlive/Cardsite-GTM are accepted, and only as cardsite-staging-deploy | iam.tf |
| Optional | Memorystore Redis (redis_enabled, off: the API runs without it), custom domains (domains, off) | redis.tf, run.tf |
| Optional: TLS edge | One 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 domains | infra/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
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.
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_variablesThe 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_IDcreates the same resources under the same names (--dry-runprints 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.GitHub variables (Settings → Secrets and variables → Actions → Variables, at repository level or on the
stagingenvironment):GCP_PROJECT_ID,GCP_REGION,GCP_WIF_PROVIDER,GCP_DEPLOY_SA, andGCP_AR_REPOif notcardsite. No secrets are stored in GitHub.First deploy: Actions → Deploy — Staging (GCP) → Run workflow (seed on). Until step 3 is done, every push to
mainstops 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):
terraform applyonce to create the bucket (outputgeoip_bucket).- 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). geoip_object = "dbip-city-lite.mmdb"instaging.tfvars, then apply. The API getsGEOIP_DB_PATHand 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):
- In
staging.tfvars:edge_host = "edge.staging.cardsite.io", and optionallypublic_host = "crd.name"andedge_acme_email. Thenterraform apply. - DNS: the A records in
terraform output edge_dns_records(each name toedge_ip). No verification step; Caddy issues each certificate once the name resolves. - With
public_host: set the GitHub variableSTAGING_PUBLIC_HOSTto the same value and redeploy, so the web build hands addresses out on it. - A customer adds a domain, points it at
edge_host(CNAME; an apex uses an A record toedge_ip) and presses Verify. The first HTTPS request gets a certificate, after the API's/internal/tls/asksays 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:
- 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/Dockerfilesays why). - Point both jobs at the new images. With the
resetinput, wipe the database (seed.sh wipe). cardsite-migrateruns 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.cardsite-seedupserts the two staging accounts (skipped only when run by hand withseedoff).- Each service gets a new revision with the new image,
apifirst. scripts/staging/smoke.shruns against the four URLs, signing in asqa@cardsite.station.centerwith the password read from Secret Manager and masked in the log.- 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-Foronly 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 toX-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-webreaches 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 whyinfra/staging/api.envraises 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 onlocalhost,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_logsrow, or the API log line for the request): it must be your own address, not a169.254.*or Google one. If it is not, setapi_trusted_proxiesto what the peer is.
Costs
Estimate at list prices in us-central1, idle-to-light QA use; confirm with
the pricing calculator.
| Item | Monthly |
|---|---|
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 | |
|---|---|
| Docker | node apps/toolkit/build.mjs, then STAGING_JWT_SECRET=$(openssl rand -hex 32) docker compose -f infra/compose.staging.yml up -d --build --wait |
| No Docker | scripts/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