Skip to main content

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​

  1. Authenticate the gcloud CLI on the machine that runs Terraform, since the stack runs the migration through it.

  2. Point image_registry at a registry you own, as image pulls need a registry you own explains, and set image_tag to the tag from your onboarding pack.

  3. Set lb_domains, or allow_plaintext_lb = true for a short trial. Without either, the plan stops with LB has no HTTPS forwarding rule.

  4. Run terraform init and terraform apply with your inputs, as in the commands above.

  5. Read the URL and check the gateway.

    curl "$(terraform output -raw lb_url)/health/readiness"
  6. Open the URL followed by /ui and sign in as admin with 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​

InputDefaultWhat it does
project_idrequiredProject to deploy into
regionus-central1
tenant, envrequiredResource name prefix
labels{}Per-deployment labels. The stack identity label is spanway-stack, since label keys cannot contain colons
create_runtimetrueCreate 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_connectiontrueCreate the Private Services Access range and connection. Set to false when the network already has one
subnet_cidr, vpc_connector_cidr10.40.0.0/16, 10.41.0.0/28Module-created ranges
lb_domains[]Domains for a managed certificate on the load balancer
allow_plaintext_lbfalseRequired to plan an HTTP-only load balancer

Images and sizing​

InputDefaultWhat it does
image_registry, image_tagregistry.spanway.ai, a pinned release tagCompose the four spanway-<component>:<tag> references. Override per component with gateway_image, backend_image, ui_image and migrations_image
gateway_cpu, gateway_memory1000m, 4GiCloud Run resource strings
backend_cpu, backend_memory1000m, 4Gi
ui_cpu, ui_memory1000m, 512Mi
gateway_min_instances, gateway_max_instances, gateway_max_instance_request_concurrency1, 10, 80Cloud Run scaling. Lower the concurrency for long LLM streams
backend_min_instances, backend_max_instances, backend_max_instance_request_concurrency1, 4, 80
ui_min_instances, ui_max_instances, ui_max_instance_request_concurrency1, 3, 200
gateway_num_workers1
gateway_connection_pool_enabled, gateway_pool_max_db_connections, gateway_pool_max_client_connfalse, 20, 1000

Database, Redis and storage​

InputDefaultWhat it does
db_tierdb-custom-2-7680Cloud SQL machine type for the writer
db_editionENTERPRISEENTERPRISE_PLUS only accepts db-perf-optimized-* tiers
db_versionPOSTGRES_16
db_name, db_usernamespanway, spanway_app
cloudsql_deletion_protectiontrue
redis_tier, redis_memory_size_gbSTANDARD_HA, 1
redis_transit_encryptiontrueMemorystore in-transit encryption. The stack injects REDIS_SSL and REDIS_SSL_CA_CERTS into Cloud Run when it is on
gcs_force_destroyfalse

Observability and metering​

InputDefaultWhat it does
gateway_metrics_portnullAdds the Prometheus metrics sidecar to the gateway service
gateway_metrics_collector_imagethe Cloud Run Managed Prometheus sidecar at a pinned versionScrapes the sidecar into Cloud Monitoring
otel_endpoint, otel_exporter, otel_headers_secret, otel_environment_name, otel_capture_message_content"", otlp_http, "", "", no_contentotel_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_secondsfalse, 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​

InputDefaultWhat it does
workflow_worker_enabledfalseAdds 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_instances2Fixed instance count, since Cloud Run scales on requests and a worker receives none
workflow_worker_cpu, workflow_worker_memory1, 2GiSize 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​

OutputWhat it is
lb_ip, lb_urlThe load balancer's anycast IP and the proxy URL. Null when create_runtime is false
gateway_service_url, backend_service_url, ui_service_urlThe default Cloud Run URLs of each service
cloudsql_writer_ip, cloudsql_reader_ip, db_username, db_namePrivate IPs and the application credentials' names
redis_endpoint, redis_host, redis_port, redis_server_ca_pemMemorystore connection details, including the CA to mount when transit encryption is on
runtime_service_account_emailThe runtime service account, for Cloud Run or GKE Workload Identity
gcs_bucketExposed to the containers as GCS_BUCKET_NAME
master_key_secret_id, db_password_secret_idSecret Manager ids. Read the master key with gcloud secrets versions access latest --secret=<id>
migration_run_commandThe gcloud run jobs execute command that re-runs the migration

Errors​

What you seeWhat it meansFix
local-exec fails with a missing commandThe 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 healthyThe 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 503The 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.