Subscribe

Deploying a Go API to ECS Fargate behind an ALB with Terraform

Part 7 of the shorty series: run the Go API on ECS Fargate (arm64) behind an Application Load Balancer with HTTPS, all in Terraform. VPC, ACM, target group health checks, the service, logs and secrets, plus checking the whole plan with terraform test and a mocked provider.

Deploying a Go API to ECS Fargate behind an ALB with Terraform

After the last part, every push to main leaves a shorty image in ECR. Nothing runs it yet. In this blog we will put it on ECS Fargate behind an Application Load Balancer, with HTTPS on a real domain name, logs in CloudWatch and the database URL read from SSM. All of it in Terraform, so it can be rebuilt or thrown away with one command.

This is part 7 of the shorty series. Level is intermediate. You should know what a task definition and a service are (ECS explained covers that) and have run plan and apply before.

I used Terraform 1.17.1 and the AWS provider 6.73.0. One thing to say upfront: I checked this code with terraform validate and with terraform test against a mocked AWS provider, which plans all 30 resources without an account. I did not create the stack in a real account while writing this post, so treat the apply section as the steps, not a transcript.

What we are building

            s.example.com (Route 53 alias)
                      |
      ALB  :80 -> 301 to :443   :443 (ACM certificate)
                      |
         target group (type ip, health check /readyz)
              /                         \
   Fargate task (arm64)          Fargate task (arm64)
   public subnet, AZ a           public subnet, AZ b
              \                         /
           Postgres (DATABASE_URL from SSM Parameter Store)
           logs -> CloudWatch Logs /ecs/shorty

The code lives in infra/app of the shorty repo, next to infra/bootstrap from part 6. It's split into network.tf, alb.tf, dns.tf, iam.tf and ecs.tf. I'll show the interesting parts of each.

Before you start

Three things must exist first. The ECR repository and at least one image tagged main, from part 6. A Route 53 public hosted zone for your domain (I use example.com and s.example.com here as placeholders). And a Postgres that the tasks can reach. Running Postgres on RDS is how I'd do that part. Its security group has to allow 5432 from the tasks' security group that we create below.

The connection string goes into SSM Parameter Store as a SecureString, by hand, so it never sits in Terraform state:

aws ssm put-parameter --name /shorty/prod/database_url --type SecureString \
  --value 'postgres://shorty:CHANGE_ME@shorty-db.abc123.ap-south-1.rds.amazonaws.com:5432/shorty?sslmode=require'

No Redis this time. shorty with an empty REDIS_URL logs a warning and reads every redirect from Postgres, which is how it was designed in part 0. ElastiCache can come later.

The network

resource "aws_subnet" "public" {
  count = length(local.azs)

  vpc_id                  = aws_vpc.main.id
  cidr_block              = cidrsubnet(var.vpc_cidr, 8, count.index)
  availability_zone       = local.azs[count.index]
  map_public_ip_on_launch = false

  tags = { Name = "shorty-public-${local.azs[count.index]}" }
}

A VPC, an internet gateway, two public subnets in two AZs and one route table. That's it. No private subnets and no NAT gateway.

This is a choice, and I want to be honest about it. The textbook layout puts the tasks in private subnets and sends their outbound traffic (pulling from ECR, writing logs, reading SSM) through a NAT gateway or VPC endpoints. A NAT gateway costs money every hour whether shorty gets traffic or not. Here the tasks sit in public subnets with a public IP, so they can reach ECR directly, and the security group lets in only the ALB on port 8080. Nothing on the internet can open a connection to them. For a small service I think that's a fair trade. When you need private subnets, building a VPC by hand shows the NAT version, and you change two lines in the service below.

The ALB needs subnets in at least two AZs anyway, so we get that for free.

The load balancer

resource "aws_lb_target_group" "shorty" {
  name        = "shorty"
  port        = 8080
  protocol    = "HTTP"
  target_type = "ip" # Fargate tasks register by IP
  vpc_id      = aws_vpc.main.id

  # Longer than SHUTDOWN_TIMEOUT (20s) is pointless, shorter cuts requests.
  deregistration_delay = 30

  health_check {
    path                = "/readyz"
    matcher             = "200"
    interval            = 10
    timeout             = 5
    healthy_threshold   = 2
    unhealthy_threshold = 3
  }
}

target_type = "ip" is required for Fargate. Tasks have no instance, the ALB sends traffic to each task's own network interface.

The health check path is /readyz, not /healthz. shorty's /readyz returns 503 when Postgres doesn't answer, so a task that lost its database stops getting traffic. /healthz always says 200 as long as the process is up. That one is for the container health check further down.

deregistration_delay is how long the ALB keeps sending in-flight requests to a task that is being stopped. The default is 300 seconds, which makes every deploy feel stuck for five minutes. shorty finishes in-flight requests within its SHUTDOWN_TIMEOUT of 20 seconds after SIGTERM, so 30 is plenty. The details of that dance are in graceful shutdown on ECS Fargate behind an ALB.

The two listeners: port 80 only redirect, port 443 forwards.

resource "aws_lb_listener" "http" {
  load_balancer_arn = aws_lb.shorty.arn
  port              = 80
  protocol          = "HTTP"

  default_action {
    type = "redirect"
    redirect {
      port        = "443"
      protocol    = "HTTPS"
      status_code = "HTTP_301"
    }
  }
}

resource "aws_lb_listener" "https" {
  load_balancer_arn = aws_lb.shorty.arn
  port              = 443
  protocol          = "HTTPS"
  ssl_policy        = "ELBSecurityPolicy-TLS13-1-2-2021-06"
  certificate_arn   = aws_acm_certificate_validation.shorty.certificate_arn

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.shorty.arn
  }
}

The certificate comes from ACM with DNS validation. Terraform creates the validation CNAME in Route 53 and aws_acm_certificate_validation waits until ACM says the certificate is issued. The listener uses the ARN from the validation resource, not from the certificate, so Terraform doesn't attach a certificate that isn't issued yet. Small thing, but it saves a confusing failed apply. That's all in dns.tf with the alias record for s.example.com.

Two IAM roles

ECS uses two roles and mixing them up is quite common. The execution role is for ECS itself: pull the image, write logs, fetch secrets before the container starts. The task role is for your code, when shorty calls AWS APIs. shorty doesn't call any, so its task role has no policies at all.

data "aws_iam_policy_document" "read_secrets" {
  statement {
    actions   = ["ssm:GetParameters"]
    resources = [local.database_url_arn]
  }
}

The execution role gets the AWS managed AmazonECSTaskExecutionRolePolicy (ECR and logs) plus this, for exactly one parameter. If your SecureString uses a customer managed KMS key instead of the default aws/ssm one, add kms:Decrypt on that key too.

The task definition

resource "aws_ecs_task_definition" "shorty" {
  family                   = "shorty"
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  cpu                      = 256
  memory                   = 512
  execution_role_arn       = aws_iam_role.execution.arn
  task_role_arn            = aws_iam_role.task.arn

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

  container_definitions = jsonencode([
    {
      name      = "shorty"
      image     = "${data.aws_ecr_repository.shorty.repository_url}:${var.image_tag}"
      essential = true

      portMappings = [{ containerPort = 8080, protocol = "tcp" }]

      environment = [
        { name = "PORT", value = "8080" },
        { name = "BASE_URL", value = "https://${var.domain_name}" },
        { name = "LOG_LEVEL", value = "info" },
        { name = "SHUTDOWN_TIMEOUT", value = "20s" },
      ]
      secrets = [
        { name = "DATABASE_URL", valueFrom = local.database_url_arn },
      ]

      user                   = "65532"
      readonlyRootFilesystem = true
      linuxParameters = {
        capabilities = { drop = ["ALL"] }
      }

      healthCheck = {
        command     = ["CMD", "/shorty", "healthcheck"]
        interval    = 10
        timeout     = 3
        retries     = 3
        startPeriod = 10
      }

      # SIGTERM, then SIGKILL after 30s. shorty needs up to 20s to drain.
      stopTimeout = 30

      logConfiguration = {
        logDriver = "awslogs"
        options = {
          awslogs-group         = aws_cloudwatch_log_group.shorty.name
          awslogs-region        = var.region
          awslogs-stream-prefix = "shorty"
        }
      }
    }
  ])
}

Most of this was paid for in earlier parts. ARM64 works because part 6 builds a multi-arch image, and Graviton Fargate is cheaper than x86 for the same size. user, readonlyRootFilesystem and dropping all capabilities are the hardening from part 4, now set by the platform. The healthCheck runs /shorty healthcheck, because distroless has no curl. And secrets puts the SSM value in the DATABASE_URL environment variable when the container starts, so the value is never in the task definition you can read from the console.

stopTimeout = 30 gives shorty time to drain before ECS sends SIGKILL. The Fargate default is also 30 and the max is 120, but I like having it written next to the 20s it relates to.

The service

resource "aws_ecs_service" "shorty" {
  name            = "shorty"
  cluster         = aws_ecs_cluster.main.id
  task_definition = aws_ecs_task_definition.shorty.arn
  desired_count   = var.desired_count
  launch_type     = "FARGATE"

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

  load_balancer {
    target_group_arn = aws_lb_target_group.shorty.arn
    container_name   = "shorty"
    container_port   = 8080
  }

  health_check_grace_period_seconds  = 30
  deployment_minimum_healthy_percent = 100
  deployment_maximum_percent         = 200

  deployment_circuit_breaker {
    enable   = true
    rollback = true
  }

  propagate_tags = "SERVICE"

  lifecycle {
    ignore_changes = [task_definition]
  }

  depends_on = [aws_lb_listener.https]
}

Two tasks, one per AZ. 100/200 means a deploy starts two new tasks next to the two old ones and only stops the old ones when the new ones are healthy. You never drop below two.

The circuit breaker watches the deploy. If new tasks keep failing to start or failing health checks, ECS marks the deployment failed and, with rollback = true, goes back to the last revision that worked. Without it, a bad image just crash loops until someone notices. This matters a lot in the next posts.

ignore_changes = [task_definition] looks odd, so here's why. Now what happens is this. Terraform creates the service with the first revision. After that, the deploy workflow from GitHub Actions registers new revisions with new image tags and moves the service to them. If Terraform didn't ignore this field, the next terraform apply would see the service on revision 9 while it knows about revision 1, and would happily roll production back. Terraform owns the shape of the task (CPU, env vars, roles), the deploy pipeline owns which image runs. If you change an env var in Terraform, it registers a new revision, and the next deploy picks it up because it starts from the latest revision of the family.

Every deploy leaves a revision behind, by the way, and they stay around until you delete them. I wrote about that in deregistering an ECS task definition does not delete it.

Checking the plan without an AWS account

terraform validate only checks the syntax and types. I wanted to see a real plan, with the count and the values, without credentials. terraform test can do that with a mocked provider. Testing Terraform with terraform test goes deeper, this is the file I used:

mock_provider "aws" {
  mock_data "aws_iam_policy_document" {
    defaults = {
      json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"
    }
  }

  override_data {
    target = data.aws_availability_zones.available
    values = { names = ["ap-south-1a", "ap-south-1b", "ap-south-1c"] }
  }
  override_data {
    target = data.aws_caller_identity.current
    values = { account_id = "111122223333" }
  }
  override_data {
    target = data.aws_ecr_repository.shorty
    values = { repository_url = "111122223333.dkr.ecr.ap-south-1.amazonaws.com/shorty" }
  }
  override_data {
    target = data.aws_route53_zone.main
    values = { zone_id = "Z0000000000EXAMPLE" }
  }
}

override_resource {
  target          = aws_acm_certificate.shorty
  override_during = plan
  values = {
    arn = "arn:aws:acm:ap-south-1:111122223333:certificate/00000000-0000-0000-0000-000000000000"
    domain_validation_options = [{
      domain_name           = "s.example.com"
      resource_record_name  = "_x1.s.example.com."
      resource_record_type  = "CNAME"
      resource_record_value = "_x2.acm-validations.aws."
    }]
  }
}

run "plan" {
  command = plan

  assert {
    condition     = aws_lb_target_group.shorty.health_check[0].path == "/readyz"
    error_message = "the ALB must check /readyz, not /healthz"
  }

  assert {
    condition     = aws_ecs_service.shorty.deployment_circuit_breaker[0].rollback
    error_message = "circuit breaker rollback must be on"
  }
}

It did not pass first time itself. Three failures, one after another.

First, "assume_role_policy" contains an invalid JSON policy: not a JSON object. See, a mocked data source returns random strings for its computed attributes, and aws_iam_policy_document.json is computed. A random string is not a policy. The mock_data block gives every policy document a valid empty policy instead.

Second, the for_each on the validation records failed with "domain_validation_options is a set of object, known only after apply". The real AWS provider fills in the domain names at plan time, the mock doesn't. An override_resource with the values fixed that, but only after I added override_during = plan (Terraform 1.11 and newer). Without it the override is only used during apply.

Third, "certificate_arn" (fioghz9m) is an invalid ARN. Once the certificate was overridden at plan time, its arn became a random string too, and the listener checks that it looks like an ARN. Giving the override a fake but valid ARN fixed it.

terraform init -backend=false
terraform test
tests/plan.tftest.hcl... in progress
  run "plan"... pass
tests/plan.tftest.hcl... tearing down
tests/plan.tftest.hcl... pass

Success! 1 passed, 0 failed.

With -verbose it prints the whole plan, ending in Plan: 30 to add, 0 to change, 0 to destroy. This test needs no credentials, so it can run in CI on every pull request. The next part does exactly that.

Applying it

With real credentials and the state bucket from the S3 state post:

cd infra/app
terraform init
terraform plan -out tfplan
terraform apply tfplan

The ACM validation is usually the slow part, a few minutes. The service will start its tasks, but the database has no tables yet, so run the migration once as a one-off task with the same task definition and a different command:

aws ecs run-task --cluster shorty --launch-type FARGATE --task-definition shorty \
  --network-configuration "awsvpcConfiguration={subnets=[$(terraform output -raw subnets)],securityGroups=[$(terraform output -raw task_security_group)],assignPublicIp=ENABLED}" \
  --overrides '{"containerOverrides":[{"name":"shorty","command":["/shorty","migrate","up"]}]}'

Overriding command works because the image uses CMD and no ENTRYPOINT, the reason is in this post on CMD vs ENTRYPOINT on ECS. The pattern of migrating in a one-off task before the service moves is the same one from running goose migrations as a one-off ECS task. Next posts automate it.

Then:

curl -si -X POST https://s.example.com/links -d '{"url":"https://go.dev/"}'
aws logs tail /ecs/shorty --follow

http:// should answer with a 301 to https://, and the JSON access logs from part 1 show up in the log tail.

What it costs and how to remove it

The ALB is billed per hour plus usage. Two Fargate tasks of 0.25 vCPU and 512 MB on arm64 are cheap but not free. Something people actually miss: every public IPv4 address costs $0.005 per hour now, and this setup has a few of them (the ALB has one per AZ, each task has one). That's still less than one NAT gateway, which is why I chose public subnets.

When you're done playing:

terraform destroy

It removes all 30 resources. The SSM parameter, the ECR images and the bootstrap stack stay, because they're not in this state.

Next part runs this Terraform from GitHub Actions: a plan on every pull request, and apply after merge with an approval.