Skip to main content

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​

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

  2. Mirror the four images into Amazon ECR, plus postgres:16-alpine when the VPC cannot reach Docker Hub, and set gateway_image, backend_image, ui_image, migrations_image and bootstrap_image in terraform.tfvars. See the images table below.

  3. Set acm_certificate_arn, or allow_plaintext_alb = true for a short trial. Without either, the plan stops with ALB has no HTTPS listener.

  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 alb_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.

Inputs​

Naming, network and TLS​

InputDefaultWhat it does
regionrequiredRegion to deploy into
tenant, envrequiredResource name prefix <tenant>-spanway-<env>
azs[]Availability zones for the module-created subnets, at least two. Unused when vpc_id is set
vpc_cidr10.40.0.0/16CIDR 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_albfalseRequired to plan an HTTP-only load balancer, for short-lived trial stacks
log_retention_days30CloudWatch retention for the three services
tags{}Per-deployment tags

Images and sizing​

InputDefaultWhat it does
gateway_image, backend_image, ui_image, migrations_imagethe four registry.spanway.ai/spanway/spanway-* images at a pinned tagPin 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_imagepostgres:16-alpineThe 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_memory1024, 4096Fargate units and MiB per gateway task
backend_cpu, backend_memory1024, 4096The backend import chain alone needs more than 1 GiB
ui_cpu, ui_memory256, 512
gateway_desired_count, backend_desired_count, ui_desired_count2, 1, 1Task counts when autoscaling is off
gateway_num_workers1Uvicorn workers per gateway task
gateway_connection_pool_enabled, gateway_pool_max_db_connections, gateway_pool_max_client_connfalse, 20, 1000In-container PgBouncer on the gateway task. Against Aurora it mints its own IAM tokens

Autoscaling​

InputDefaultWhat it does
gateway_autoscaling_enabled, gateway_min_capacity, gateway_max_capacitytrue, 1, 10Application Auto Scaling on the gateway service
gateway_cpu_target, gateway_memory_target70, 80Target-tracking percentages. Set gateway_memory_target to 0 to scale on CPU only
gateway_target_requests_per_second0Adds an ALBRequestCountPerTarget policy. The value is per task per second
gateway_target_tokens_per_second, gateway_tokens_metric0, nullAdds 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_targettrue, 1, 4, 70
ui_autoscaling_enabled, ui_min_capacity, ui_max_capacity, ui_cpu_targetfalse, 1, 3, 80

Database, Redis and storage​

InputDefaultWhat it does
create_databasetrueCreate 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_classdb.r6g.largeWriter and reader instance class
db_engine_version16.4Aurora PostgreSQL version
db_name, db_master_username, db_usernamespanway, postgres, spanway_appDatabase name, the bootstrap-only master user and the IAM-authenticated application user
skip_final_snapshotfalseDestroying the cluster takes a final snapshot unless this is true
create_redistrueCreate 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_replicascache.t4g.small, 1Zero replicas gives a single node for development
s3_force_destroyfalseAllow terraform destroy to empty the bucket

Observability and metering​

InputDefaultWhat it does
gateway_metrics_portnullAdds 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_secondsfalse, 4010, 512, 2048, 1000, fallback, 10Collector 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​

InputDefaultWhat it does
workflow_worker_enabledfalseAdds 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_memory2, 1024, 2048Size of the worker service
workflow_worker_drain_seconds90How 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_targetfalse, 2, 20, 70Target tracking on CPU
workflow_worker_backlog_metric, workflow_worker_target_backlog_per_workernull, 4A 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​

OutputWhat it is
alb_dns_name, alb_urlThe load balancer name and the proxy URL. The scheme follows acm_certificate_arn
ecs_clusterCluster name
vpc_id, task_security_group_idThe VPC in use and the tasks' security group, which an existing database or Redis should allow inbound from
aurora_writer_endpoint, aurora_reader_endpointNull when create_database = false
redis_endpointTLS endpoint, null when create_redis = false
s3_bucketExposed to the containers as S3_BUCKET_NAME and S3_REGION_NAME
master_key_secret_arnWhere the master key lives. Read it with aws secretsmanager get-secret-value --secret-id <arn>
db_master_password_secret_arn, db_bootstrap_sqlThe bootstrap credentials and SQL, for re-running the role setup by hand
migration_run_commandThe aws ecs run-task command that re-runs the migration

Errors​

What you seeWhat it meansFix
local-exec fails with a missing commandThe 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 healthyThe 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-alpineThe 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-* imageThe images are private during the preview.Mirror them to ECR and set the image inputs.
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​

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.