Skip to Content
Runlane
Run in productionDeploy to AWS

Deploy with Terraform

Deploy the tutorial app with Terraform, the AWS provider, and a Docker image build.

Finish Prepare the app first. This page adds Terraform to that app. It creates a Postgres database, three SQS queues, two Lambda functions, a maintenance timer, and a container worker. Amazon Simple Queue Service (SQS) holds messages that wake workers.

The shared maintenance entry point uses runlane.createMaintenanceHandler() and starts lazily. Export the handler directly; it ignores event and context arguments.

Before you start

Install Terraform 1.17.1 or a later 1.x release for your platform. Use Node.js 24 and keep Docker running. The Docker provider builds and pushes the worker image during deploy.

Configure AWS CLI credentials for a disposable account. Your deploy identity needs permission to create these resources, pass their roles, and push images. Store and pull the app's images with Amazon Elastic Container Registry (ECR).

Run commands from the app root unless a step says otherwise. Check your tools and AWS account:

terminal
terraform version
docker info
aws sts get-caller-identity

Use one region throughout. The example uses us-east-1. Keep the runlane-tutorial names free in that account and region.

This exercise uses a public database and test data. It has no deletion protection or final snapshot. Review the network trade-offs before deploying. The resources cost money until you remove them.

Add Terraform to the app

Create a directory for the configuration:

terminal
mkdir terraform

Create terraform/versions.tf. Exact provider versions keep provider behavior stable. Commit the generated .terraform.lock.hcl file with your configuration.

terraform/versions.tf
terraform {
  required_version = ">= 1.17.1, < 2.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "= 6.71.0"
    }
    archive = {
      source  = "hashicorp/archive"
      version = "= 2.8.1"
    }
    random = {
      source  = "hashicorp/random"
      version = "= 3.9.1"
    }
    docker = {
      source  = "kreuzwerker/docker"
      version = "= 4.6.0"
    }
  }
}

provider "aws" {
  region = var.region
}

data "aws_ecr_authorization_token" "current" {}

provider "docker" {
  registry_auth {
    address  = trimprefix(data.aws_ecr_authorization_token.current.proxy_endpoint, "https://")
    username = data.aws_ecr_authorization_token.current.user_name
    password = data.aws_ecr_authorization_token.current.password
  }
}

The AWS provider reads your local AWS credentials. The Docker provider uses a short-lived ECR login from AWS.

terraform/variables.tf
variable "region" {
  description = "AWS region for every tutorial resource."
  type        = string
  default     = "us-east-1"
}

locals {
  name = "runlane-tutorial"
}

Set the region in a variable file:

terraform/terraform.tfvars
region = "us-east-1"

Append these entries to the app's .gitignore:

.gitignore
.env*
terraform/.terraform/
terraform/*.tfstate*
terraform/*.tfplan

Append this entry to the existing .dockerignore. It keeps Terraform state, credentials, and Lambda archives out of the image build context:

.dockerignore
terraform/

This tutorial uses local state. State holds the database password in plain text, even though its output is marked sensitive. Keep state, saved plans, and .env private. Production needs an encrypted remote backend with access controls.

Define the infrastructure

Network

A virtual private cloud (VPC) is your AWS network. A subnet is a range of addresses inside it. These public subnets span two Availability Zones, separate locations within the region. Plain resources keep the small network and its routes visible; no module is needed.

terraform/network.tf
data "aws_availability_zones" "available" {
  state = "available"
}

resource "aws_vpc" "app" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = { Name = local.name }
}

resource "aws_internet_gateway" "app" {
  vpc_id = aws_vpc.app.id
}

resource "aws_subnet" "public" {
  count = 2

  vpc_id                  = aws_vpc.app.id
  availability_zone       = data.aws_availability_zones.available.names[count.index]
  cidr_block              = cidrsubnet(aws_vpc.app.cidr_block, 8, count.index)
  map_public_ip_on_launch = true

  tags = { Name = "${local.name}-public-${count.index + 1}" }
}

resource "aws_route_table" "public" {
  vpc_id = aws_vpc.app.id

  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.app.id
  }
}

resource "aws_route_table_association" "public" {
  count = 2

  subnet_id      = aws_subnet.public[count.index].id
  route_table_id = aws_route_table.public.id
}

resource "aws_security_group" "database" {
  name   = "${local.name}-database"
  vpc_id = aws_vpc.app.id
}

resource "aws_vpc_security_group_ingress_rule" "database" {
  security_group_id = aws_security_group.database.id
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "tcp"
  from_port         = 5432
  to_port           = 5432
}

resource "aws_security_group" "worker" {
  name   = "${local.name}-worker"
  vpc_id = aws_vpc.app.id
}

resource "aws_vpc_security_group_egress_rule" "worker" {
  security_group_id = aws_security_group.worker.id
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "-1"
}

A security group holds network access rules. The database allows connection attempts on port 5432 from any IPv4 address. Lambda runs outside this VPC and has no fixed outbound IP. The worker gets a public IP and needs no inbound rule.

There is no NAT gateway, which would give private workloads outbound internet access. Public subnets let the worker reach ECR and SQS directly. A private database needs an in-VPC path for workloads, migrations, and CLI checks. Follow Prepare for production before real use.

Database

terraform/database.tf
resource "random_password" "database" {
  length  = 32
  special = false
}

resource "aws_db_subnet_group" "app" {
  name       = local.name
  subnet_ids = aws_subnet.public[*].id
}

resource "aws_db_instance" "app" {
  identifier              = local.name
  engine                  = "postgres"
  engine_version          = "17"
  instance_class          = "db.t4g.micro"
  allocated_storage       = 20
  storage_type            = "gp3"
  storage_encrypted       = true
  db_name                 = "runlane"
  username                = "runlane"
  password                = random_password.database.result
  db_subnet_group_name    = aws_db_subnet_group.app.name
  vpc_security_group_ids  = [aws_security_group.database.id]
  publicly_accessible     = true
  deletion_protection     = false
  skip_final_snapshot     = true
  backup_retention_period = 0

  depends_on = [
    aws_route_table_association.public,
    aws_vpc_security_group_ingress_rule.database,
  ]
}

locals {
  database_url = "postgresql://runlane:${random_password.database.result}@${aws_db_instance.app.endpoint}/runlane?sslmode=verify-full"
}

RDS hosts PostgreSQL 17. The generated password has 32 letters and digits, so it fits in the URL without escaping. sslmode=verify-full checks the certificate and hostname. Each process also needs the CA bundle from Prepare the app.

Queues

terraform/queues.tf
resource "aws_sqs_queue" "dead_letter" {
  name                      = "${local.name}-dead-letter"
  message_retention_seconds = 1209600
}

resource "aws_sqs_queue" "work" {
  for_each = toset(["default", "long-running"])

  name                       = "${local.name}-${each.key}"
  visibility_timeout_seconds = 360
  redrive_policy = jsonencode({
    deadLetterTargetArn = aws_sqs_queue.dead_letter.arn
    maxReceiveCount     = 5
  })
}

A dead-letter queue (DLQ) holds messages after repeated delivery failures. Both work queues send messages there after five receives. The DLQ retains them for 14 days. The six-minute visibility timeout hides received messages while a consumer handles them. It follows the Lambda SQS timeout rule.

Lambda roles and assets

An IAM role is an AWS identity with permission policies. Each function gets a separate role. Delivery can receive from default and publish to both work queues. Maintenance can publish to both.

terraform/functions.tf
locals {
  runtime_env = {
    DATABASE_URL                   = local.database_url
    RUNLANE_ENVIRONMENT            = "tutorial"
    RUNLANE_DEFAULT_QUEUE_URL      = aws_sqs_queue.work["default"].url
    RUNLANE_LONG_RUNNING_QUEUE_URL = aws_sqs_queue.work["long-running"].url
  }

  lambda_sqs_statements = {
    maintenance = [{
      Effect   = "Allow"
      Action   = ["sqs:SendMessage"]
      Resource = [for queue in aws_sqs_queue.work : queue.arn]
    }]
    delivery = [
      {
        Effect   = "Allow"
        Action   = ["sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes"]
        Resource = [aws_sqs_queue.work["default"].arn]
      },
      {
        Effect   = "Allow"
        Action   = ["sqs:SendMessage"]
        Resource = [for queue in aws_sqs_queue.work : queue.arn]
      },
    ]
  }
}

data "archive_file" "lambda" {
  type        = "zip"
  source_dir  = "${path.module}/../dist/lambda"
  output_path = "${path.module}/.terraform/lambda.zip"
}

resource "aws_cloudwatch_log_group" "lambda" {
  for_each = local.lambda_sqs_statements

  name              = "/aws/lambda/${local.name}-${each.key}"
  retention_in_days = 7
}

resource "aws_iam_role" "lambda" {
  for_each = local.lambda_sqs_statements

  name = "${local.name}-${each.key}"
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "lambda.amazonaws.com" }
      Action    = "sts:AssumeRole"
    }]
  })
}

resource "aws_iam_role_policy" "lambda" {
  for_each = local.lambda_sqs_statements

  role = aws_iam_role.lambda[each.key].id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = concat([{
      Effect   = "Allow"
      Action   = ["logs:CreateLogStream", "logs:PutLogEvents"]
      Resource = "${aws_cloudwatch_log_group.lambda[each.key].arn}:*"
    }], each.value)
  })
}

resource "aws_lambda_function" "delivery" {
  function_name    = "${local.name}-delivery"
  role             = aws_iam_role.lambda["delivery"].arn
  runtime          = "nodejs24.x"
  architectures    = ["x86_64"]
  handler          = "delivery.handler"
  timeout          = 60
  memory_size      = 512
  filename         = data.archive_file.lambda.output_path
  source_code_hash = data.archive_file.lambda.output_base64sha256

  environment {
    variables = merge(local.runtime_env, {
      NODE_EXTRA_CA_CERTS = "/var/task/certificates/rds-global-bundle.pem"
    })
  }

  depends_on = [aws_iam_role_policy.lambda["delivery"], terraform_data.migrations]
}

resource "aws_lambda_function" "maintenance" {
  function_name    = "${local.name}-maintenance"
  role             = aws_iam_role.lambda["maintenance"].arn
  runtime          = "nodejs24.x"
  architectures    = ["x86_64"]
  handler          = "maintenance.handler"
  timeout          = 120
  memory_size      = 512
  filename         = data.archive_file.lambda.output_path
  source_code_hash = data.archive_file.lambda.output_base64sha256

  environment {
    variables = merge(local.runtime_env, {
      NODE_EXTRA_CA_CERTS = "/var/task/certificates/rds-global-bundle.pem"
    })
  }

  depends_on = [aws_iam_role_policy.lambda["maintenance"], terraform_data.migrations]
}

The AWS provider supports nodejs24.x. Each role policy depends on its log group. Each function waits for that policy, so the one-week retention is set before the function exists. Lambda supplies AWS_REGION itself.

The archive preserves the asset layout from the app build. It holds the delivery and maintenance bundles and CA file. source_code_hash tells Terraform when code has changed.

Migrations and delivery

terraform/migrations.tf
resource "terraform_data" "migrations" {
  triggers_replace = timestamp()

  provisioner "local-exec" {
    working_dir = abspath("${path.module}/..")
    command     = "npm exec -- runlane adapter postgres migrate"
    environment = merge(local.runtime_env, {
      AWS_REGION          = var.region
      NODE_EXTRA_CA_CERTS = abspath("${path.module}/../certificates/rds-global-bundle.pem")
    })
  }

  depends_on = [aws_db_instance.app, aws_sqs_queue.work]
}

resource "aws_lambda_event_source_mapping" "delivery" {
  event_source_arn        = aws_sqs_queue.work["default"].arn
  function_name           = aws_lambda_function.delivery.arn
  batch_size              = 10
  function_response_types = ["ReportBatchItemFailures"]

  scaling_config {
    maximum_concurrency = 2
  }

  depends_on = [terraform_data.migrations]
}

The timestamp replaces terraform_data on every apply. Its local-exec runs from the app root on the deploying machine after the database and queues exist. It supplies the runtime environment and an absolute CA path before Node starts. It does not run on destroy.

A failing provisioner fails the apply by default. Keep that default. The database URL is sensitive, so Terraform suppresses normal provisioner output. Failure details can still include command output. Keep deploy logs private. If migrations fail, save the current database and queue values as shown below. Then run the migration command from the app root to read its output. Fix the cause and apply again.

This machine can reach the tutorial's public database. Production needs a release step with private database access.

An event source mapping polls SQS and invokes Lambda. This mapping handles up to ten messages per batch and two batches at once. Partial batch responses let Lambda retry only failed messages. No function reserved concurrency is set; new accounts may lack quota for it.

The delivery and maintenance functions wait for migrations, as do the mapping, timer, and worker service. Existing workloads can keep running during an update. Keep schema changes compatible with their code; see Deploy task changes.

Maintenance timer

EventBridge Scheduler is an AWS timer service. Its role can invoke only the maintenance function.

terraform/schedule.tf
resource "aws_iam_role" "scheduler" {
  name = "${local.name}-scheduler"
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "scheduler.amazonaws.com" }
      Action    = "sts:AssumeRole"
    }]
  })
}

resource "aws_iam_role_policy" "scheduler" {
  role = aws_iam_role.scheduler.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = ["lambda:InvokeFunction"]
      Resource = aws_lambda_function.maintenance.arn
    }]
  })
}

resource "aws_scheduler_schedule" "maintenance" {
  name                = "${local.name}-maintenance"
  schedule_expression = "rate(1 minute)"

  flexible_time_window {
    mode = "OFF"
  }

  target {
    arn      = aws_lambda_function.maintenance.arn
    role_arn = aws_iam_role.scheduler.arn
    input    = jsonencode({})
  }

  depends_on = [aws_iam_role_policy.scheduler, terraform_data.migrations]
}

The timer invokes maintenance once per minute. It starts only after the role policy and migration step succeed.

Worker image and roles

Fargate runs containers without servers for you to manage. Use Amazon Elastic Container Service (ECS) to keep this worker running. Its execution role pulls the image and writes logs. Its task role grants the app's SQS access.

terraform/worker.tf
locals {
  worker_files = setunion(
    toset(["Dockerfile", ".dockerignore", "certificates/rds-global-bundle.pem"]),
    toset([for file in fileset("${path.module}/../dist/worker", "**") : "dist/worker/${file}"]),
  )
  worker_hash = sha256(jsonencode({
    for file in local.worker_files : file => filesha256("${path.module}/../${file}")
  }))
  ecs_assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "ecs-tasks.amazonaws.com" }
      Action    = "sts:AssumeRole"
    }]
  })
}

resource "aws_ecr_repository" "worker" {
  name         = "${local.name}-worker"
  force_delete = true
}

resource "docker_registry_image" "worker" {
  name          = "${aws_ecr_repository.worker.repository_url}:${local.worker_hash}"
  keep_remotely = true

  build {
    context    = abspath("${path.module}/..")
    dockerfile = "Dockerfile"
    platform   = "linux/amd64"
  }
}

resource "aws_cloudwatch_log_group" "worker" {
  name              = "/ecs/${local.name}-worker"
  retention_in_days = 7
}

resource "aws_iam_role" "execution" {
  name               = "${local.name}-execution"
  assume_role_policy = local.ecs_assume_role_policy
}

resource "aws_iam_role_policy" "execution" {
  role = aws_iam_role.execution.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect   = "Allow"
        Action   = ["ecr:GetAuthorizationToken"]
        Resource = "*"
      },
      {
        Effect   = "Allow"
        Action   = ["ecr:BatchCheckLayerAvailability", "ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage"]
        Resource = aws_ecr_repository.worker.arn
      },
      {
        Effect   = "Allow"
        Action   = ["logs:CreateLogStream", "logs:PutLogEvents"]
        Resource = "${aws_cloudwatch_log_group.worker.arn}:*"
      },
    ]
  })
}

resource "aws_iam_role" "worker" {
  name               = "${local.name}-worker"
  assume_role_policy = local.ecs_assume_role_policy
}

resource "aws_iam_role_policy" "worker" {
  role = aws_iam_role.worker.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect   = "Allow"
        Action   = ["sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:ChangeMessageVisibility"]
        Resource = aws_sqs_queue.work["long-running"].arn
      },
      {
        Effect   = "Allow"
        Action   = ["sqs:SendMessage"]
        Resource = [for queue in aws_sqs_queue.work : queue.arn]
      },
    ]
  })
}

resource "aws_ecs_cluster" "app" {
  name = local.name
}

resource "aws_ecs_task_definition" "worker" {
  family                   = "${local.name}-worker"
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  cpu                      = "256"
  memory                   = "512"
  execution_role_arn       = aws_iam_role.execution.arn
  task_role_arn            = aws_iam_role.worker.arn

  runtime_platform {
    operating_system_family = "LINUX"
    cpu_architecture        = "X86_64"
  }

  container_definitions = jsonencode([{
    name        = "worker"
    image       = "${aws_ecr_repository.worker.repository_url}@${docker_registry_image.worker.sha256_digest}"
    essential   = true
    stopTimeout = 60
    environment = [for name, value in merge(local.runtime_env, {
      AWS_REGION          = var.region
      NODE_EXTRA_CA_CERTS = "/app/certificates/rds-global-bundle.pem"
    }) : { name = name, value = value }]
    logConfiguration = {
      logDriver = "awslogs"
      options = {
        awslogs-group         = aws_cloudwatch_log_group.worker.name
        awslogs-region        = var.region
        awslogs-stream-prefix = "worker"
      }
    }
  }])
}

resource "aws_ecs_service" "worker" {
  name                  = "${local.name}-worker"
  cluster               = aws_ecs_cluster.app.id
  task_definition       = aws_ecs_task_definition.worker.arn
  launch_type           = "FARGATE"
  desired_count         = 1
  wait_for_steady_state = true

  network_configuration {
    subnets          = aws_subnet.public[*].id
    security_groups  = [aws_security_group.worker.id]
    assign_public_ip = true
  }

  deployment_circuit_breaker {
    enable   = true
    rollback = true
  }

  depends_on = [
    terraform_data.migrations,
    aws_iam_role_policy.execution,
    aws_iam_role_policy.worker,
    aws_route_table_association.public,
    aws_vpc_security_group_egress_rule.worker,
  ]
}

The registry image resource builds and pushes in one step. Its tag hashes the worker bundle, Dockerfile, ignore file, and CA bundle. A changed input creates a new image. Old images stay in ECR for rollback; force_delete removes them when the repository is destroyed.

A task definition describes the container's image, resources, roles, and settings. It uses the pushed image's digest, an exact content identifier. A changed digest creates a new task revision and service rollout. The worker has 0.25 vCPU, 0.5 GB memory, and an explicit AWS_REGION. Its stopTimeout gives it 60 seconds to drain after SIGTERM.

The service waits for steady state. Its circuit breaker detects a failed rollout and can roll back to a prior successful deployment. Check the active task revision after a rollback; steady state alone does not prove the new code is running.

Outputs

terraform/outputs.tf
output "databaseUrl" {
  description = "Database connection URL. Keep it secret."
  value       = local.database_url
  sensitive   = true
}

output "defaultQueueUrl" {
  value = aws_sqs_queue.work["default"].url
}

output "longRunningQueueUrl" {
  value = aws_sqs_queue.work["long-running"].url
}

output "deadLetterQueueUrl" {
  value = aws_sqs_queue.dead_letter.url
}

output "region" {
  value = var.region
}

output "deliveryFunctionName" {
  value = aws_lambda_function.delivery.function_name
}

output "maintenanceFunctionName" {
  value = aws_lambda_function.maintenance.function_name
}

output "workerLogGroup" {
  value = aws_cloudwatch_log_group.worker.name
}

output "clusterName" {
  value = aws_ecs_cluster.app.name
}

output "serviceName" {
  value = aws_ecs_service.worker.name
}

These names match Check the deployment. Terraform hides databaseUrl in normal output; terraform output -raw databaseUrl reveals it.

Deploy

From the app root, build before every apply:

terminal
npm run build
terraform -chdir=terraform init
terraform -chdir=terraform fmt
terraform -chdir=terraform validate
terraform -chdir=terraform plan
terraform -chdir=terraform apply

Review the plan, then approve the apply when prompted. RDS creation takes several minutes. Terraform uploads the Lambda archives and builds and pushes the worker image. It runs migrations before it starts or updates workloads. A failed migration stops those dependent changes.

Later applies still replace the migration resource because its timestamp changes. This reruns migrations even when the app code is unchanged. Unrelated resources can change in parallel. Terraform does not roll back an entire failed apply.

Save the outputs for the CLI

From the app root, write the values into .env. This overwrites that file and limits access to your user:

terminal
umask 077
cat > .env <<EOF
DATABASE_URL=$(terraform -chdir=terraform output -raw databaseUrl)
RUNLANE_ENVIRONMENT=tutorial
RUNLANE_DEFAULT_QUEUE_URL=$(terraform -chdir=terraform output -raw defaultQueueUrl)
RUNLANE_LONG_RUNNING_QUEUE_URL=$(terraform -chdir=terraform output -raw longRunningQueueUrl)
AWS_REGION=$(terraform -chdir=terraform output -raw region)
EOF
chmod 600 .env
export AWS_REGION="$(terraform -chdir=terraform output -raw region)"
export NODE_EXTRA_CA_CERTS="$PWD/certificates/rds-global-bundle.pem"

Keep .env out of source control. Remove stale .env.local values if they would override this file. Export the CA path before starting Node so it trusts the RDS certificate.

Read the other outputs without exposing the database URL:

terminal
terraform -chdir=terraform output -raw deadLetterQueueUrl
terraform -chdir=terraform output -raw deliveryFunctionName
terraform -chdir=terraform output -raw maintenanceFunctionName
terraform -chdir=terraform output -raw workerLogGroup
terraform -chdir=terraform output -raw clusterName
terraform -chdir=terraform output -raw serviceName

Check it works

Follow Check the deployment. Run a greeting and a report, then prove the maintenance timer releases a future run.

Remove everything

This deletes the database and its data without a final snapshot. From the app root:

terminal
terraform -chdir=terraform destroy
terraform -chdir=terraform state list

Review the destroy plan and approve it. On success, state list is empty. Destroy removes the database, all three queues, functions, timer, ECS service and cluster, roles, and all three log groups. It removes the ECR repository and all its images, then the subnets and VPC. Confirm these resources are gone in the AWS console.

The local state files and .env still need private handling. Once teardown is confirmed, remove .env if you no longer need it.

Troubleshoot Terraform

SymptomFix
Terraform cannot find dist/lambdaRun npm run build from the app root before planning or applying.
Docker connection or image build errorStart Docker. Check docker info. If needed, set DOCKER_CONTEXT to the context used by your Docker CLI. If Docker uses the containerd image store, switch to the classic store for this path.
Migration command failsSave the current env values using the steps above. Run npm exec -- runlane adapter postgres migrate from the app root with the CA path exported. Read its output, fix the cause, then apply again.
ECS becomes stable after rolling backInspect its deployment events and task definition revision. Fix the startup error and apply the corrected image. A rollback restores service; it does not deploy the new code.
Resource name already existsUse a separate account or region for this exercise, or remove a prior tutorial deployment with its original state. Keep the state needed to manage your resources.

For TLS, database, SQS, and task errors, use the shared troubleshooting guide.

On this page