Terraform on AWS
The AWS stack provisions a VPC with public and private subnets and one NAT gateway, an Aurora PostgreSQL cluster with a writer and a reader and IAM database authentication, an ElastiCache for Redis replication group with encryption at rest and in transit, a private versioned S3 bucket, Secrets Manager entries for the master key and the Aurora bootstrap password, an ECS Fargate cluster running the gateway, backend and ui services, an Application Load Balancer with path routing, and a one-off migration task definition. It is the stack described on the Terraform overview, with the inputs that are specific to AWS listed here.
cd terraform/spanway/aws/examples/default
cp terraform.tfvars.example terraform.tfvars
export TF_VAR_spanway_master_key="sk-..."
terraform init
terraform apply -var acm_certificate_arn=arn:aws:acm:us-west-2:111122223333:certificate/example -var region=us-west-2 -var 'azs=["us-west-2a","us-west-2b"]' -var tenant=examplecorp -var env=prod
terraform output alb_url
terraform apply needs the aws CLI installed and authenticated, because the stack runs the database bootstrap and the schema migration through local-exec provisioners.
A real-world scenario
A platform team wants a production gateway on AWS 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 aws CLI, review the plan, apply it, and sign in to the Admin UI at the load balancer URL.
Steps
-
Authenticate the
awsCLI on the machine that runs Terraform, since the stack runs the migration through it. -
Mirror the four images into Amazon ECR, plus
postgres:16-alpinewhen the VPC cannot reach Docker Hub, and setgateway_image,backend_image,ui_image,migrations_imageandbootstrap_imageinterraform.tfvars. See the images table below. -
Set
acm_certificate_arn, orallow_plaintext_alb = truefor a short trial. Without either, the plan stops withALB has no HTTPS listener. -
Run
terraform initandterraform applywith your inputs, as in the commands above. -
Read the URL and check the gateway.
curl "$(terraform output -raw alb_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.
Inputs
Naming, network and TLS
| Input | Default | What it does |
|---|---|---|
region | required | Region to deploy into |
tenant, env | required | Resource name prefix <tenant>-spanway-<env> |
azs | [] | Availability zones for the module-created subnets, at least two. Unused when vpc_id is set |
vpc_cidr | 10.40.0.0/16 | CIDR of the module-created VPC |
vpc_id, public_subnet_ids, private_subnet_ids | "", [], [] | Bring your own network. When vpc_id is set no VPC, subnet, gateway or route table is created. The private subnets need their own egress |
additional_task_security_group_ids | [] | Extra security groups attached to the ECS tasks |
acm_certificate_arn | "" | Certificate for a 443 listener. Port 80 then redirects to HTTPS |
allow_plaintext_alb | false | Required to plan an HTTP-only load balancer, for short-lived trial stacks |
log_retention_days | 30 | CloudWatch retention for the three services |
tags | {} | Per-deployment tags |
Images and sizing
| Input | Default | What it does |
|---|---|---|
gateway_image, backend_image, ui_image, migrations_image | the four registry.spanway.ai/spanway/spanway-* images at a pinned tag | Pin all four to the same release. The images are private during the preview and the task definitions carry no registry credentials, so mirror the four images into Amazon ECR in the same account and set these inputs to the ECR addresses. The example root takes them in terraform.tfvars. The default tag v2.0.0 only resolves once 2.0.0 is released. The registry address and pull credentials for the mirror step are in your onboarding pack |
bootstrap_image | postgres:16-alpine | The Postgres client image the one-shot database bootstrap task runs, pulled from Docker Hub. Point it at an ECR mirror when the VPC has no Docker Hub egress or hits Docker Hub rate limits |
gateway_cpu, gateway_memory | 1024, 4096 | Fargate units and MiB per gateway task |
backend_cpu, backend_memory | 1024, 4096 | The backend import chain alone needs more than 1 GiB |
ui_cpu, ui_memory | 256, 512 | |
gateway_desired_count, backend_desired_count, ui_desired_count | 2, 1, 1 | Task counts when autoscaling is off |
gateway_num_workers | 1 | Uvicorn workers per gateway task |
gateway_connection_pool_enabled, gateway_pool_max_db_connections, gateway_pool_max_client_conn | false, 20, 1000 | In-container PgBouncer on the gateway task. Against Aurora it mints its own IAM tokens |
Autoscaling
| Input | Default | What it does |
|---|---|---|
gateway_autoscaling_enabled, gateway_min_capacity, gateway_max_capacity | true, 1, 10 | Application Auto Scaling on the gateway service |
gateway_cpu_target, gateway_memory_target | 70, 80 | Target-tracking percentages. Set gateway_memory_target to 0 to scale on CPU only |
gateway_target_requests_per_second | 0 | Adds an ALBRequestCountPerTarget policy. The value is per task per second |
gateway_target_tokens_per_second, gateway_tokens_metric | 0, null | Adds a metric-math policy over a CloudWatch metric you publish from the metrics sidecar, with gateway_tokens_metric naming its namespace and dimensions |
backend_autoscaling_enabled, backend_min_capacity, backend_max_capacity, backend_cpu_target | true, 1, 4, 70 | |
ui_autoscaling_enabled, ui_min_capacity, ui_max_capacity, ui_cpu_target | false, 1, 3, 80 |
Database, Redis and storage
| Input | Default | What it does |
|---|---|---|
create_database | true | Create the Aurora cluster. Set to false and pass database_url to use a Postgres you already run, or leave the URL empty to run without a database |
database_url | "" | Connection string for an existing database, stored in Secrets Manager and injected as DATABASE_URL |
db_instance_class | db.r6g.large | Writer and reader instance class |
db_engine_version | 16.4 | Aurora PostgreSQL version |
db_name, db_master_username, db_username | spanway, postgres, spanway_app | Database name, the bootstrap-only master user and the IAM-authenticated application user |
skip_final_snapshot | false | Destroying the cluster takes a final snapshot unless this is true |
create_redis | true | Create the ElastiCache replication group. Set to false and pass redis_url for an existing Redis |
redis_url | "" | Existing Redis, injected as REDIS_URL |
redis_node_type, redis_num_replicas | cache.t4g.small, 1 | Zero replicas gives a single node for development |
s3_force_destroy | false | Allow terraform destroy to empty the bucket |
Observability and metering
| Input | Default | What it does |
|---|---|---|
gateway_metrics_port | null | Adds a Prometheus metrics sidecar to the gateway task on this port |
gateway_metrics_scrape_cidrs | [] | CIDRs the task security group opens that port to |
otel_endpoint, otel_exporter, otel_environment_name, otel_capture_message_content, otel_headers_secret_arn | "", otlp_http, "", no_content, "" | OpenTelemetry export, off until the endpoint is set |
billing_metrics_endpoint, billing_metrics_client_cert_pem, billing_metrics_client_key_pem, billing_metrics_ca_cert_pem | "" | The PEMs are written to Secrets Manager and injected as SPANWAY_BILLING_METRICS_CLIENT_CERT, _CLIENT_KEY and _CA_CERT |
collector_enabled, collector_port, collector_cpu, collector_memory, collector_buffer_size, collector_on_unavailable, collector_drain_timeout_seconds | false, 4010, 512, 2048, 1000, fallback, 10 | Collector sidecar. Its CPU and memory are carved out of the gateway task's allocation |
The proxy_config map is YAML-encoded and uploaded to S3 as config/spanway-config.yaml. The gateway and backend entrypoints download it to /tmp/spanway-config.yaml at task start and set CONFIG_FILE_PATH. The object's etag is part of the task definition, so a config change rolls both services. gateway_extra_secrets and backend_extra_secrets take Secrets Manager ARNs, with the ECS :field:: suffix to pick a key out of a JSON secret, and the execution role gains secretsmanager:GetSecretValue on each one.
Workflow workers
| Input | Default | What it does |
|---|---|---|
workflow_worker_enabled | false | Adds an ECS 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_desired_count, workflow_worker_cpu, workflow_worker_memory | 2, 1024, 2048 | Size of the worker service |
workflow_worker_drain_seconds | 90 | How long a stopping worker keeps running its steps. The task's stopTimeout is ten seconds longer, and Fargate caps it at 120, so the most is 110 |
workflow_worker_extra_env, workflow_worker_extra_secrets | {} | Extra env vars and Secrets Manager ARNs for the worker |
workflow_worker_autoscaling_enabled, workflow_worker_min_capacity, workflow_worker_max_capacity, workflow_worker_cpu_target | false, 2, 20, 70 | Target tracking on CPU |
workflow_worker_backlog_metric, workflow_worker_target_backlog_per_worker | null, 4 | A CloudWatch metric carrying spanway_workflow_runner_backlog_per_worker, which then becomes the main scaling signal |
The workers run the gateway image, sit behind no load balancer and get their own security group with no inbound rules. The module-created Aurora and ElastiCache groups let that group in, and an existing database must allow it or a group passed in additional_task_security_group_ids.
Database bootstrap and migration
Aurora is created with IAM authentication enabled, but a Postgres role still has to exist and hold rds_iam. bootstrap.tf does that during apply with a one-shot Fargate task that runs idempotent SQL as the master user, from bootstrap_image. The same apply then runs the migration task from migrations_image. The task definition <name>-migrations gets 512 CPU units and 4 GiB because the Prisma engine peaks above 1 GiB while applying a schema, and the gateway and backend services depend on it. At runtime the proxy assembles DATABASE_URL from DATABASE_HOST, DATABASE_PORT, DATABASE_USER and DATABASE_NAME plus a short-lived IAM token, and the task role is allowed rds-db:connect on the application user only. With create_database = false the migration still runs on every apply, against your URL.
Outputs
| Output | What it is |
|---|---|
alb_dns_name, alb_url | The load balancer name and the proxy URL. The scheme follows acm_certificate_arn |
ecs_cluster | Cluster name |
vpc_id, task_security_group_id | The VPC in use and the tasks' security group, which an existing database or Redis should allow inbound from |
aurora_writer_endpoint, aurora_reader_endpoint | Null when create_database = false |
redis_endpoint | TLS endpoint, null when create_redis = false |
s3_bucket | Exposed to the containers as S3_BUCKET_NAME and S3_REGION_NAME |
master_key_secret_arn | Where the master key lives. Read it with aws secretsmanager get-secret-value --secret-id <arn> |
db_master_password_secret_arn, db_bootstrap_sql | The bootstrap credentials and SQL, for re-running the role setup by hand |
migration_run_command | The aws ecs run-task command that re-runs the migration |
Errors
| What you see | What it means | Fix |
|---|---|---|
local-exec fails with a missing command | The aws 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. |
ALB has no HTTPS listener. Either set acm_certificate_arn to enable TLS, or set allow_plaintext_alb = true to opt into HTTP-only (trial / dev only). | Neither a certificate nor the plaintext opt-in is set. | Set acm_certificate_arn, or allow_plaintext_alb = true for a trial. |
The bootstrap task stops with CannotPullContainerError for postgres:16-alpine | The VPC cannot reach Docker Hub or hit its rate limit. | Mirror the image to ECR and set bootstrap_image. |
Tasks stop with CannotPullContainerError for a spanway-* image | The images are private during the preview. | Mirror them to ECR and set the image inputs. |
| 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
Every task writes to CloudWatch Logs under /ecs/<tenant>-spanway-<env>/, with one log group per component: gateway, backend, ui, migrations, bootstrap-db and, with workers on, workflow-worker. Retention is log_retention_days. The bootstrap-db group shows the SQL the bootstrap ran and ends without an error when the role exists. The migrations group ends with Migration job completed successfully., or with Migration job failed after retries. after the Prisma error. The log reference explains both.
Related
- Terraform overview for the inputs every stack shares.
- Terraform provider to manage keys and models as code afterwards.
- Container images.