Terraform on GCP
The GCP stack provisions a VPC with a Private Services Access range and a Serverless VPC Access connector, a Cloud SQL for PostgreSQL primary with a cross-zone read replica, a Memorystore for Redis instance on a private IP, a private versioned Cloud Storage bucket, Secret Manager entries for the master key and the database password, three Cloud Run v2 services (gateway, backend, ui) on a shared runtime service account, a Cloud Run job for the migration, and a global external HTTP(S) load balancer with serverless NEGs and a URL map that splits traffic between the three services. The inputs it shares with the other clouds are on the Terraform overview.
cd terraform/spanway/gcp/examples/default
cp terraform.tfvars.example terraform.tfvars
terraform init
terraform apply
terraform output lb_url
gcloud must be authenticated and the Run, SQL Admin, Redis, Secret Manager, VPC Access, Compute, Service Networking, Storage and Artifact Registry APIs enabled. The example root also carries a Cloud Shell tutorial for a guided first deploy.
A real-world scenario
A platform team wants a production gateway on Google Cloud with a managed database, cache and object store, created and changed through code review like the rest of their infrastructure. They run the stack from a CI runner that has the gcloud CLI, review the plan, apply it, and sign in to the Admin UI at the load balancer URL.
Steps
-
Authenticate the
gcloudCLI on the machine that runs Terraform, since the stack runs the migration through it. -
Point
image_registryat a registry you own, as image pulls need a registry you own explains, and setimage_tagto the tag from your onboarding pack. -
Set
lb_domains, orallow_plaintext_lb = truefor a short trial. Without either, the plan stops withLB has no HTTPS forwarding rule. -
Run
terraform initandterraform applywith your inputs, as in the commands above. -
Read the URL and check the gateway.
curl "$(terraform output -raw lb_url)/health/readiness" -
Open the URL followed by
/uiand sign in asadminwith the master key from the secret store the stack used.
Expected result
terraform apply finishes after the migration task, /health/readiness reports the database as connected, and the Admin UI opens at the load balancer URL.
Image pulls need a registry you own
Cloud Run only pulls from Artifact Registry, gcr.io and docker.io, and rejects the registry.spanway.ai defaults at apply time. The images are also private during the preview, with the registry address and pull credentials in your onboarding pack. Either create an Artifact Registry remote repository backed by that registry, with the pull credentials stored in Secret Manager, once per project and point image_registry at it, or mirror the four images into a regular repository and set the per-component *_image inputs.
gcloud artifacts repositories create spanway --repository-format=docker \
--location=us-central1 --mode=remote-repository \
--remote-docker-repo=https://registry.spanway.ai
image_registry = "us-central1-docker.pkg.dev/my-project/spanway/images"
image_tag = "<release tag>"
Inputs
Project, naming and network
| Input | Default | What it does |
|---|---|---|
project_id | required | Project to deploy into |
region | us-central1 | |
tenant, env | required | Resource name prefix |
labels | {} | Per-deployment labels. The stack identity label is spanway-stack, since label keys cannot contain colons |
create_runtime | true | Create Cloud Run, the load balancer, the VPC connector and the migration job. Set to false to provision only the dependencies for GKE |
network_id | "" | Existing VPC network resource id. When set no VPC or subnet is created |
create_psa_connection | true | Create the Private Services Access range and connection. Set to false when the network already has one |
subnet_cidr, vpc_connector_cidr | 10.40.0.0/16, 10.41.0.0/28 | Module-created ranges |
lb_domains | [] | Domains for a managed certificate on the load balancer |
allow_plaintext_lb | false | Required to plan an HTTP-only load balancer |
Images and sizing
| Input | Default | What it does |
|---|---|---|
image_registry, image_tag | registry.spanway.ai, a pinned release tag | Compose the four spanway-<component>:<tag> references. Override per component with gateway_image, backend_image, ui_image and migrations_image |
gateway_cpu, gateway_memory | 1000m, 4Gi | Cloud Run resource strings |
backend_cpu, backend_memory | 1000m, 4Gi | |
ui_cpu, ui_memory | 1000m, 512Mi | |
gateway_min_instances, gateway_max_instances, gateway_max_instance_request_concurrency | 1, 10, 80 | Cloud Run scaling. Lower the concurrency for long LLM streams |
backend_min_instances, backend_max_instances, backend_max_instance_request_concurrency | 1, 4, 80 | |
ui_min_instances, ui_max_instances, ui_max_instance_request_concurrency | 1, 3, 200 | |
gateway_num_workers | 1 | |
gateway_connection_pool_enabled, gateway_pool_max_db_connections, gateway_pool_max_client_conn | false, 20, 1000 |
Database, Redis and storage
| Input | Default | What it does |
|---|---|---|
db_tier | db-custom-2-7680 | Cloud SQL machine type for the writer |
db_edition | ENTERPRISE | ENTERPRISE_PLUS only accepts db-perf-optimized-* tiers |
db_version | POSTGRES_16 | |
db_name, db_username | spanway, spanway_app | |
cloudsql_deletion_protection | true | |
redis_tier, redis_memory_size_gb | STANDARD_HA, 1 | |
redis_transit_encryption | true | Memorystore in-transit encryption. The stack injects REDIS_SSL and REDIS_SSL_CA_CERTS into Cloud Run when it is on |
gcs_force_destroy | false |
Observability and metering
| Input | Default | What it does |
|---|---|---|
gateway_metrics_port | null | Adds the Prometheus metrics sidecar to the gateway service |
gateway_metrics_collector_image | the Cloud Run Managed Prometheus sidecar at a pinned version | Scrapes the sidecar into Cloud Monitoring |
otel_endpoint, otel_exporter, otel_headers_secret, otel_environment_name, otel_capture_message_content | "", otlp_http, "", "", no_content | otel_headers_secret is a Secret Manager resource id |
billing_metrics_endpoint, billing_metrics_client_cert_pem, billing_metrics_client_key_pem, billing_metrics_ca_cert_pem | "" | |
collector_enabled, collector_port, collector_cpu, collector_memory, collector_buffer_size, collector_on_unavailable, collector_drain_timeout_seconds | false, 4010, 1000m, 2Gi, 1000, fallback, 10 |
gateway_extra_secrets and backend_extra_secrets take Secret Manager resource ids and arrive in the container through value_source.secret_key_ref.
Workflow workers
| Input | Default | What it does |
|---|---|---|
workflow_worker_enabled | false | Adds a Cloud Run service that runs workflow runner steps and makes the gateway and backend producers. Needs the workflow_runner and workflow_queue_workers license features |
workflow_worker_instances | 2 | Fixed instance count, since Cloud Run scales on requests and a worker receives none |
workflow_worker_cpu, workflow_worker_memory | 1, 2Gi | Size of a worker instance |
workflow_worker_extra_env | {} | Extra env vars for the worker |
The worker service accepts internal traffic only, has no invoker binding and keeps its CPU allocated between requests. Cloud Run gives a stopping instance about 10 seconds, so the drain window is 8 seconds and steps cut off after that are handed back to the queue or picked up again once their lease runs out.
Database authentication and migration
The proxy's IAM token support is for AWS RDS, so this stack uses password authentication. A random password is generated, stored in Secret Manager as <name>-db-password and handed to each Cloud Run service as DATABASE_PASSWORD, and the container entrypoint assembles DATABASE_URL and DATABASE_URL_READ_REPLICA from DATABASE_HOST and that password before starting, so the password never appears in a service spec or a log line. The migration runs as the spanway-migrations Cloud Run job, triggered by bootstrap.tf during apply with gcloud run jobs execute, and the gateway and backend services wait for it.
Dependencies only, for GKE
With create_runtime = false the stack creates Cloud SQL, Memorystore, the bucket, the secrets and the runtime service account, and nothing else. For a Shared VPC pass network_id and set create_psa_connection = false once the host project has configured Private Services Access. Map the outputs into the componentised Helm chart values: cloudsql_writer_ip and cloudsql_reader_ip become database.writer.host and database.reader.host, db_name becomes dbname, and redis_host and redis_port become redis.host and redis.port, with Kubernetes Secrets for the password and master key.
Outputs
| Output | What it is |
|---|---|
lb_ip, lb_url | The load balancer's anycast IP and the proxy URL. Null when create_runtime is false |
gateway_service_url, backend_service_url, ui_service_url | The default Cloud Run URLs of each service |
cloudsql_writer_ip, cloudsql_reader_ip, db_username, db_name | Private IPs and the application credentials' names |
redis_endpoint, redis_host, redis_port, redis_server_ca_pem | Memorystore connection details, including the CA to mount when transit encryption is on |
runtime_service_account_email | The runtime service account, for Cloud Run or GKE Workload Identity |
gcs_bucket | Exposed to the containers as GCS_BUCKET_NAME |
master_key_secret_id, db_password_secret_id | Secret Manager ids. Read the master key with gcloud secrets versions access latest --secret=<id> |
migration_run_command | The gcloud run jobs execute command that re-runs the migration |
Errors
| What you see | What it means | Fix |
|---|---|---|
local-exec fails with a missing command | The gcloud CLI is not installed or not signed in where Terraform runs. | Install and authenticate it, or run the migration_run_command output by hand. |
| The services never become healthy | The migration did not run, so the schema is missing. | Run terraform output migration_run_command and execute it. |
LB has no HTTPS forwarding rule. Either set lb_domains to a list of DNS names you want a Google-managed cert for, or set allow_plaintext_lb = true to opt into HTTP-only (trial / dev only). | Neither a domain nor the plaintext opt-in is set. | Set lb_domains, or allow_plaintext_lb = true for a trial. |
| The load balancer answers 502 or 503 | The gateway tasks are still starting or failing their health check. | Read the gateway logs in the cloud console. |
Logs
Cloud Run sends each service's output to Cloud Logging. Open Logging, Logs Explorer in the console and pick the service <tenant>-spanway-<env>-gateway, -backend or -ui, or the job <tenant>-spanway-<env>-migrations. A successful migration execution ends with Migration job completed successfully., and a failed one with Migration job failed after retries. after the Prisma error, as the log reference explains.
Related
- Terraform overview for the inputs every stack shares.
- Terraform provider to manage keys and models as code afterwards.
- Container images.