---
title: Modules
description: The five Terraform modules, the bootstrap stack, and the contract between them.
sidebar:
  icon: boxes
---

The modules are plain resources with no community registry modules and no provider or backend blocks. Every module takes `name` (for example `patent-prod`) and `tags`, and names each resource `${name}-<purpose>`. The environments call them in dependency order: observability, network, data, service, then edge.

- infrastructure/
  - bootstrap/
    - main.tf
    - iam.tf
  - github/
    - main.tf
    - variables.tf
    - providers.tf
  - modules/
    - observability/
    - network/
    - data/
    - service/
      - acm.tf
      - alb.tf
      - alarms.tf
      - autoscaling.tf
      - ecr.tf
      - ecs.tf
      - iam.tf
      - security_groups.tf
    - edge/
      - main.tf
      - site.tf
      - waf.tf
      - dns.tf
  - envs/
    - dev/
    - staging/
    - prod/

Every environment has the same `main.tf`, `variables.tf`, `providers.tf` and `outputs.tf`. Only `backend.tf` (the state key) and `terraform.tfvars` differ.

## Observability

The alarm destination and the shared log encryption key. The SNS topic is encrypted with its own KMS key, and both the topic policy and the key policy let CloudWatch alarms in this account publish to it.

| Inputs | Outputs |
|---|---|
| `name`, `tags`, `alarm_email` | `alarm_topic_arn`, `logs_kms_key_arn` |

### Walkthrough

**Lookups and locals**

```hcl modules/observability/main.tf
data "aws_caller_identity" "current" {}
data "aws_partition" "current" {}
data "aws_region" "current" {}

locals {
  account_id = data.aws_caller_identity.current.account_id
  partition  = data.aws_partition.current.partition
  region     = data.aws_region.current.region
}
```

- `data "aws_caller_identity" "current"`: reads the account ID of the credentials Terraform runs with, so policies can name this account without a variable.
- `data "aws_partition" "current"`: reads the partition (`aws`, `aws-cn`, `aws-us-gov`), so ARNs built by string interpolation stay valid outside the commercial partition.
- `data "aws_region" "current"`: reads the region of the provider, used for the regional Logs service principal and for alarm and log group ARNs.
- `account_id`, `partition`, `region`: short local names for the three values, so the policy documents read `local.account_id` instead of the full data source path.

**Alarm topic key policy — `aws_iam_policy_document.alarms_key`**

```hcl modules/observability/main.tf
data "aws_iam_policy_document" "alarms_key" {
  # Standard statement: lets IAM policies in this account delegate use of the key.
  statement {
    sid       = "EnableIamPolicies"
    actions   = ["kms:*"]
    resources = ["*"]

    principals {
      type        = "AWS"
      identifiers = ["arn:${local.partition}:iam::${local.account_id}:root"]
    }
  }

  # CloudWatch needs these two actions to publish to a topic encrypted with a customer managed key.
  statement {
    sid       = "AllowCloudWatchAlarmsToPublish"
    actions   = ["kms:Decrypt", "kms:GenerateDataKey*"]
    resources = ["*"]

    principals {
      type        = "Service"
      identifiers = ["cloudwatch.amazonaws.com"]
    }

    # Confused-deputy guard: only alarms in this account may use the key.
    condition {
      test     = "StringEquals"
      variable = "aws:SourceAccount"
      values   = [local.account_id]
    }

    condition {
      test     = "ArnLike"
      variable = "aws:SourceArn"
      values   = ["arn:${local.partition}:cloudwatch:${local.region}:${local.account_id}:alarm:*"]
    }
  }
}
```

- `data "aws_iam_policy_document" "alarms_key"`: builds the KMS key policy as JSON from HCL, which avoids hand-written JSON and lets Terraform reference account and partition values.
- `statement "EnableIamPolicies"`: the standard root statement. A KMS key is only usable through IAM if its key policy delegates to the account, so without it IAM policies in this account have no effect on the key.
  - `actions = ["kms:*"]`, `resources = ["*"]`: all KMS actions. In a key policy `"*"` means this key only.
  - `principals` of type `AWS` with `arn:${local.partition}:iam::${local.account_id}:root`: the account root, which means "any IAM principal in this account that an IAM policy allows".
- `statement "AllowCloudWatchAlarmsToPublish"`: lets CloudWatch alarms publish to a topic encrypted with this key. SNS must decrypt and generate data keys on behalf of the publisher, and CloudWatch is not an IAM principal in this account.
  - `actions = ["kms:Decrypt", "kms:GenerateDataKey*"]`: the two actions CloudWatch needs; nothing else is granted.
  - `principals` of type `Service` with `cloudwatch.amazonaws.com`: the CloudWatch service principal.
  - `condition` `StringEquals` on `aws:SourceAccount`: confused-deputy guard. Only calls made for alarms owned by this account are accepted, so another account's alarm cannot use the key through the shared service principal.
  - `condition` `ArnLike` on `aws:SourceArn`: narrows further to alarm ARNs in this account and region (`...:alarm:*`), so other CloudWatch resource types cannot use the key.

**Alarm topic key — `aws_kms_key.alarms`, `aws_kms_alias.alarms`**

```hcl modules/observability/main.tf
resource "aws_kms_key" "alarms" {
  description = "${var.name} alarm topic encryption"
  policy      = data.aws_iam_policy_document.alarms_key.json

  # Rotation limits exposure of a single key version.
  enable_key_rotation = true

  tags = merge(var.tags, { Name = "${var.name}-alarms" })
}

resource "aws_kms_alias" "alarms" {
  name          = "alias/${var.name}-alarms"
  target_key_id = aws_kms_key.alarms.key_id
}
```

- `description = "${var.name} alarm topic encryption"`: shows the key's purpose in the console. `${var.name}` is the module's name prefix, which keeps resources from several environments distinguishable.
- `policy = data.aws_iam_policy_document.alarms_key.json`: attaches the policy document above. Without it AWS applies the default key policy and CloudWatch could not publish.
- `enable_key_rotation = true`: AWS rotates the key material every year, which limits the data exposed by any single key version. Old versions are kept so existing ciphertext still decrypts.
- `tags = merge(var.tags, { Name = "${var.name}-alarms" })`: the caller's tags (`var.tags`, default `{}`) plus a `Name` tag for the console.
- `aws_kms_alias.alarms`: a friendly name for the key.
  - `name = "alias/${var.name}-alarms"`: KMS requires the `alias/` prefix. The alias lets people and logs refer to the key by name rather than by key ID.
  - `target_key_id = aws_kms_key.alarms.key_id`: binds the alias to the key.

**Alarm topic — `aws_sns_topic.alarms`**

```hcl modules/observability/main.tf
resource "aws_sns_topic" "alarms" {
  name = "${var.name}-alarms"

  # The AWS managed SNS key cannot grant CloudWatch access, so a customer managed key is required.
  kms_master_key_id = aws_kms_key.alarms.arn

  tags = merge(var.tags, { Name = "${var.name}-alarms" })
}
```

- `name = "${var.name}-alarms"`: the topic every CloudWatch alarm in the stack notifies. Other modules receive its ARN through the `alarm_topic_arn` output.
- `kms_master_key_id = aws_kms_key.alarms.arn`: encrypts messages at rest. The AWS managed key `alias/aws/sns` has a fixed key policy that cannot grant CloudWatch access, so alarm notifications would fail to publish; a customer managed key is required.
- `tags = merge(...)`: standard tags plus a Name tag.

**Alarm topic policy — `aws_iam_policy_document.alarms_topic`, `aws_sns_topic_policy.alarms`**

```hcl modules/observability/main.tf
data "aws_iam_policy_document" "alarms_topic" {
  # Keeps the SNS default: principals in this account manage and use the topic.
  statement {
    sid = "AllowAccountManageTopic"
    actions = [
      "SNS:Subscribe",
      "SNS:SetTopicAttributes",
      "SNS:RemovePermission",
      "SNS:Receive",
      "SNS:Publish",
      "SNS:ListSubscriptionsByTopic",
      "SNS:GetTopicAttributes",
      "SNS:DeleteTopic",
      "SNS:AddPermission",
    ]
    resources = [aws_sns_topic.alarms.arn]

    principals {
      type        = "AWS"
      identifiers = ["*"]
    }

    condition {
      test     = "StringEquals"
      variable = "AWS:SourceOwner"
      values   = [local.account_id]
    }
  }

  statement {
    sid       = "AllowCloudWatchAlarmsToPublish"
    actions   = ["sns:Publish"]
    resources = [aws_sns_topic.alarms.arn]

    principals {
      type        = "Service"
      identifiers = ["cloudwatch.amazonaws.com"]
    }

    # Confused-deputy guard: only alarms in this account may publish.
    condition {
      test     = "StringEquals"
      variable = "aws:SourceAccount"
      values   = [local.account_id]
    }

    condition {
      test     = "ArnLike"
      variable = "aws:SourceArn"
      values   = ["arn:${local.partition}:cloudwatch:${local.region}:${local.account_id}:alarm:*"]
    }
  }
}

resource "aws_sns_topic_policy" "alarms" {
  arn    = aws_sns_topic.alarms.arn
  policy = data.aws_iam_policy_document.alarms_topic.json
}
```

- `data "aws_iam_policy_document" "alarms_topic"`: the topic's resource policy. Setting a policy replaces the SNS default, so the default statement is restated and the CloudWatch statement added.
- `statement "AllowAccountManageTopic"`: reproduces the SNS default policy.
  - `actions`: the nine standard SNS topic actions (subscribe, receive, publish, list subscriptions, read and set attributes, add and remove permission, delete). Dropping this statement would lock account principals out of managing the topic through the policy.
  - `resources = [aws_sns_topic.alarms.arn]`: this topic only.
  - `principals` type `AWS` with `identifiers = ["*"]`: any principal, constrained by the condition below.
  - `condition` `StringEquals` on `AWS:SourceOwner` with the account ID: the `*` principal is limited to callers from this account, as in the SNS default.
- `statement "AllowCloudWatchAlarmsToPublish"`: lets alarms publish.
  - `actions = ["sns:Publish"]`: publish only.
  - `resources = [aws_sns_topic.alarms.arn]`: this topic only.
  - `principals` type `Service`, `cloudwatch.amazonaws.com`: CloudWatch is the caller, not an IAM user or role.
  - `condition` `aws:SourceAccount`: confused-deputy guard; only alarms in this account may publish.
  - `condition` `aws:SourceArn` with `ArnLike` on `...:alarm:*` in this account and region: only alarm resources, not other CloudWatch features.
- `aws_sns_topic_policy.alarms`: attaches the document to the topic.
  - `arn = aws_sns_topic.alarms.arn`: the topic to attach to. The policy is a separate resource because the document references the topic ARN, and an inline policy on the topic would be a cycle.
  - `policy = ...json`: the rendered JSON.

**Email subscription — `aws_sns_topic_subscription.email`**

```hcl modules/observability/main.tf
resource "aws_sns_topic_subscription" "email" {
  count = var.alarm_email == null ? 0 : 1

  topic_arn = aws_sns_topic.alarms.arn
  protocol  = "email"
  endpoint  = var.alarm_email
}
```

- `count = var.alarm_email == null ? 0 : 1`: creates the subscription only when an address is supplied. With `alarm_email = null` the topic exists with no subscriber, and other endpoints can be attached outside this module.
- `topic_arn = aws_sns_topic.alarms.arn`: the topic to subscribe to.
- `protocol = "email"`: delivery by email. The recipient must click the confirmation link AWS sends; until then no alarm mail is delivered and Terraform shows the subscription as pending.
- `endpoint = var.alarm_email`: the address that receives alarms.

**Log group key policy — `aws_iam_policy_document.logs_key`**

```hcl modules/observability/main.tf
data "aws_iam_policy_document" "logs_key" {
  # Standard statement: lets IAM policies in this account delegate use of the key.
  statement {
    sid       = "EnableIamPolicies"
    actions   = ["kms:*"]
    resources = ["*"]

    principals {
      type        = "AWS"
      identifiers = ["arn:${local.partition}:iam::${local.account_id}:root"]
    }
  }

  statement {
    sid = "AllowCloudWatchLogs"
    actions = [
      "kms:Encrypt",
      "kms:Decrypt",
      "kms:ReEncrypt*",
      "kms:GenerateDataKey*",
      "kms:Describe*",
    ]
    resources = ["*"]

    # The Logs service principal is regional and must match the key's region.
    principals {
      type        = "Service"
      identifiers = ["logs.${local.region}.amazonaws.com"]
    }

    # Limits the key to log groups of this account and region, whatever their name.
    condition {
      test     = "ArnLike"
      variable = "kms:EncryptionContext:aws:logs:arn"
      values   = ["arn:${local.partition}:logs:${local.region}:${local.account_id}:log-group:*"]
    }
  }
}
```

- `data "aws_iam_policy_document" "logs_key"`: key policy for the key that encrypts CloudWatch log groups across the stack (VPC flow logs, service logs). Other modules receive its ARN as `logs_kms_key_arn`.
- `statement "EnableIamPolicies"`: same root-delegation statement as on the alarm key; without it IAM policies cannot grant access to the key.
- `statement "AllowCloudWatchLogs"`: lets the Logs service encrypt and decrypt log data.
  - `actions`: `kms:Encrypt`, `kms:Decrypt`, `kms:ReEncrypt*`, `kms:GenerateDataKey*` and `kms:Describe*`, the set CloudWatch Logs needs to protect log events and to check the key when a log group is associated with it.
  - `resources = ["*"]`: this key.
  - `principals` type `Service` with `logs.${local.region}.amazonaws.com`: the Logs principal is regional, so the principal must name the region the key lives in. Log groups in other regions cannot use this key.
  - `condition` `ArnLike` on `kms:EncryptionContext:aws:logs:arn` with `log-group:*` in this account and region: Logs passes the log group ARN as encryption context. The condition limits use to log groups of this account and region, whatever their name, so the key does not need to know group names and creating the key does not depend on the groups.

**Log group key — `aws_kms_key.logs`, `aws_kms_alias.logs`**

```hcl modules/observability/main.tf
resource "aws_kms_key" "logs" {
  description = "${var.name} CloudWatch log group encryption"
  policy      = data.aws_iam_policy_document.logs_key.json

  # Rotation limits exposure of a single key version.
  enable_key_rotation = true

  tags = merge(var.tags, { Name = "${var.name}-logs" })
}

resource "aws_kms_alias" "logs" {
  name          = "alias/${var.name}-logs"
  target_key_id = aws_kms_key.logs.key_id
}
```

- `description = "${var.name} CloudWatch log group encryption"`: states the purpose in the console.
- `policy = data.aws_iam_policy_document.logs_key.json`: attaches the policy above.
- `enable_key_rotation = true`: annual rotation, as on the alarm key.
- `tags = merge(...)`: standard tags plus a Name tag.
- `aws_kms_alias.logs`: `alias/${var.name}-logs` pointing at `aws_kms_key.logs.key_id`, the same named handle as for the alarm key.

## Network

Three subnet tiers in each AZ:

- **Public:** NAT gateways only.
- **Private:** the ALB, the tasks and the VPC endpoints.
- **Data:** no route to the internet.

There is always an S3 gateway endpoint. Interface endpoints for ECR, Logs and Secrets Manager are optional. Flow logs go to an encrypted log group, and the default security group has no rules.

| Inputs | Outputs |
|---|---|
| `name`, `tags`, `vpc_cidr`, `az_count`, `single_nat_gateway`, `enable_interface_endpoints`, `flow_log_retention_days`, `logs_kms_key_arn` | `vpc_id`, `vpc_cidr_block`, `public_subnet_ids`, `private_subnet_ids`, `data_subnet_ids`, `nat_public_ips` |

### Walkthrough

#### main.tf

**Lookups and locals**

```hcl modules/network/main.tf
data "aws_availability_zones" "available" {
  state = "available"
}

data "aws_region" "current" {}
data "aws_caller_identity" "current" {}
data "aws_partition" "current" {}

locals {
  azs = slice(data.aws_availability_zones.available.names, 0, var.az_count)

  # CIDR plan, in units of the VPC size (shown for a /16; other sizes scale the same way):
  #   private: /20 (4 newbits), indexes 0..2   -> 10.0.0.0/20, 10.0.16.0/20, 10.0.32.0/20 (4091 usable each, Fargate ENIs)
  #   data:    /24 (8 newbits), indexes 48..50 -> 10.0.48.0/24 ...
  #   public:  /24 (8 newbits), indexes 64..66 -> 10.0.64.0/24 ... (NAT gateways only)
  # The ranges never overlap, and 10.0.80.0 and up stays free for new tiers.
  private_cidrs = [for i in range(var.az_count) : cidrsubnet(var.vpc_cidr, 4, i)]
  data_cidrs    = [for i in range(var.az_count) : cidrsubnet(var.vpc_cidr, 8, 48 + i)]
  public_cidrs  = [for i in range(var.az_count) : cidrsubnet(var.vpc_cidr, 8, 64 + i)]

  nat_count = var.single_nat_gateway ? 1 : var.az_count

  region     = data.aws_region.current.region
  partition  = data.aws_partition.current.partition
  account_id = data.aws_caller_identity.current.account_id

  interface_endpoints = var.enable_interface_endpoints ? toset(["ecr.api", "ecr.dkr", "logs", "secretsmanager"]) : toset([])
}
```

- `data "aws_availability_zones" "available"`: lists the AZs in the current region.
  - `state = "available"`: skips AZs that are impaired or not opted in, so subnets are never placed in one that cannot launch resources.
- `data "aws_region" "current"`, `data "aws_caller_identity" "current"`, `data "aws_partition" "current"`: read the region, account ID and partition (`aws`, `aws-cn`, ...) of the credentials Terraform runs with. They feed endpoint service names and IAM conditions without extra variables, and keep ARNs valid outside the `aws` partition.
- `azs = slice(..., 0, var.az_count)`: the first `az_count` AZ names. The provider returns them sorted, so the choice is stable between runs.
- CIDR plan comment: sizes are fractions of the VPC, so the same expressions work for any /16 to /20. For a /16 such as `10.0.0.0/16`:
  - `cidrsubnet(prefix, newbits, index)` adds `newbits` to the prefix length and picks the `index`-th block of that size. 4 new bits turn /16 into /20 (4096 addresses); 8 new bits turn it into /24 (256 addresses).
  - Private: /20, index `0..2` gives `10.0.0.0/20`, `10.0.16.0/20`, `10.0.32.0/20`. Each has 4091 usable addresses (AWS reserves five), which matters because every Fargate task takes an ENI plus the interface endpoints and the ALB.
  - Data: /24, index `48 + i`. Block 48 of 256 starts at 48 x 256 = 12288 addresses in, which is `10.0.48.0`, directly after the last private /20 ends at `10.0.47.255`.
  - Public: /24, index `64 + i` starts at `10.0.64.0`. Only NAT gateways live here, so a /24 is ample.
  - Nothing overlaps, and `10.0.80.0` upward stays unallocated for a new tier. For a /20 VPC the same indexes give /24 private and /28 data and public blocks, laid out in the same proportions.
- `private_cidrs`, `data_cidrs`, `public_cidrs`: one `cidrsubnet` per AZ, indexed by position, so AZ N always gets the same range. Changing `az_count` from 2 to 3 adds a block without moving the others.
- `nat_count = var.single_nat_gateway ? 1 : var.az_count`: how many NAT gateways and Elastic IPs to create. One shared gateway is cheaper; one per AZ keeps egress alive when an AZ fails.
- `region`, `partition`, `account_id`: short aliases for the three lookups above.
- `interface_endpoints`: the set of interface endpoint service suffixes. It is `toset([])` when `enable_interface_endpoints` is false, so the `for_each` further down creates nothing. A set (not a list) gives each endpoint a stable key in state, so removing one entry does not renumber the others.

**VPC and default security group — `aws_vpc.this`, `aws_default_security_group.this`**

```hcl modules/network/main.tf
resource "aws_vpc" "this" {
  cidr_block = var.vpc_cidr
  # Interface endpoints with private DNS need both settings.
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = merge(var.tags, { Name = "${var.name}-vpc" })
}

# Lock down the default security group: no rules, so nothing can use it by accident.
resource "aws_default_security_group" "this" {
  vpc_id = aws_vpc.this.id

  tags = merge(var.tags, { Name = "${var.name}-default-sg" })
}
```

- `resource "aws_vpc" "this"`: the VPC every other resource attaches to.
  - `cidr_block = var.vpc_cidr`: the range the subnet plan above is cut from.
  - `enable_dns_support`, `enable_dns_hostnames = true`: the VPC resolver must be on, or the private DNS names of the interface endpoints would not resolve to their in-VPC addresses and ECR, Logs and Secrets Manager calls would go out via NAT instead.
  - `tags = merge(var.tags, { Name = "${var.name}-vpc" })`: standard tags from the caller plus a Name tag with the shared `var.name` prefix, so resources are identifiable in the console.
- `resource "aws_default_security_group" "this"`: adopts the group AWS creates with every VPC.
  - `vpc_id`: the VPC whose default group is managed.
  - No ingress or egress blocks: Terraform removes the default allow rules, leaving a group with none, so nothing attached to it by accident gets connectivity.
  - `tags`: standard tags plus a Name tag.

**Internet gateway — `aws_internet_gateway.this`**

```hcl modules/network/main.tf
# Required for NAT, and CloudFront VPC origins require an internet gateway on the VPC.
resource "aws_internet_gateway" "this" {
  vpc_id = aws_vpc.this.id

  tags = merge(var.tags, { Name = "${var.name}-igw" })
}
```

- `vpc_id`: attaches the gateway to the VPC.
- Comment: the public route table sends NAT gateway traffic through it, and the CloudFront VPC origin used by the edge module requires the VPC to have an internet gateway.
- `tags`: standard tags plus a Name tag.

**Public subnets — `aws_subnet.public`**

```hcl modules/network/main.tf
resource "aws_subnet" "public" {
  count = var.az_count

  vpc_id            = aws_vpc.this.id
  availability_zone = local.azs[count.index]
  cidr_block        = local.public_cidrs[count.index]
  # Only the NAT gateways get public addresses (their Elastic IPs).
  map_public_ip_on_launch = false

  tags = merge(var.tags, { Name = "${var.name}-public-${local.azs[count.index]}", Tier = "public" })
}
```

- `count = var.az_count`: one subnet per AZ.
- `vpc_id`: parent VPC.
- `availability_zone = local.azs[count.index]`: subnet N lives in AZ N.
- `cidr_block = local.public_cidrs[count.index]`: the /24 computed in `locals`.
- `map_public_ip_on_launch = false`: instances launched here do not get a public IPv4 address automatically. The only public addresses are the NAT gateway Elastic IPs.
- `tags`: standard tags, a Name tag including the AZ, and `Tier = "public"` for filtering.

**Private subnets — `aws_subnet.private`**

```hcl modules/network/main.tf
resource "aws_subnet" "private" {
  count = var.az_count

  vpc_id                  = aws_vpc.this.id
  availability_zone       = local.azs[count.index]
  cidr_block              = local.private_cidrs[count.index]
  map_public_ip_on_launch = false

  tags = merge(var.tags, { Name = "${var.name}-private-${local.azs[count.index]}", Tier = "private" })
}
```

- `count`, `vpc_id`, `availability_zone`: one subnet per AZ in the same VPC, as for the public tier.
- `cidr_block = local.private_cidrs[count.index]`: the large /20 block that holds the ALB, Fargate task ENIs and interface endpoint ENIs.
- `map_public_ip_on_launch = false`: tasks never get public addresses; outbound traffic goes through NAT.
- `tags`: standard tags, Name with the AZ, and `Tier = "private"`.

**Data subnets — `aws_subnet.data`**

```hcl modules/network/main.tf
resource "aws_subnet" "data" {
  count = var.az_count

  vpc_id                  = aws_vpc.this.id
  availability_zone       = local.azs[count.index]
  cidr_block              = local.data_cidrs[count.index]
  map_public_ip_on_launch = false

  tags = merge(var.tags, { Name = "${var.name}-data-${local.azs[count.index]}", Tier = "data" })
}
```

- `count`, `vpc_id`, `availability_zone`: one per AZ.
- `cidr_block = local.data_cidrs[count.index]`: a /24 per AZ for the Aurora instances. Database subnets need few addresses.
- `map_public_ip_on_launch = false`: no public addresses; this tier also has no internet route (see its route table below).
- `tags`: standard tags, Name with the AZ, and `Tier = "data"`.

**NAT gateways — `aws_eip.nat`, `aws_nat_gateway.this`**

```hcl modules/network/main.tf
resource "aws_eip" "nat" {
  count = local.nat_count

  domain = "vpc"

  tags = merge(var.tags, { Name = "${var.name}-nat-${count.index}" })

  depends_on = [aws_internet_gateway.this]
}

resource "aws_nat_gateway" "this" {
  count = local.nat_count

  allocation_id = aws_eip.nat[count.index].id
  subnet_id     = aws_subnet.public[count.index].id

  tags = merge(var.tags, { Name = "${var.name}-nat-${count.index}" })

  depends_on = [aws_internet_gateway.this]
}
```

- `resource "aws_eip" "nat"`: the fixed public address each NAT gateway uses.
  - `count = local.nat_count`: one address per gateway (one in total with `single_nat_gateway`).
  - `domain = "vpc"`: allocates the address for use in a VPC. This replaces the removed `vpc = true` argument.
  - `tags`: standard tags plus a Name tag with the gateway index.
  - `depends_on = [aws_internet_gateway.this]`: an Elastic IP needs the internet gateway attached to the VPC; the dependency is not visible through attributes, so it is explicit. The same applies to the NAT gateway.
- `resource "aws_nat_gateway" "this"`: lets private subnets reach the internet outbound only.
  - `count = local.nat_count`: same count as the addresses, so index N pairs with address N.
  - `allocation_id = aws_eip.nat[count.index].id`: binds the Elastic IP, which is the stable egress address output as `nat_public_ips` for allow-lists.
  - `subnet_id = aws_subnet.public[count.index].id`: a NAT gateway must sit in a public subnet. With a single gateway it lands in the first AZ.
  - `tags`: standard tags plus a Name tag.

**Public routing — `aws_route_table.public`, `aws_route.public_internet`, `aws_route_table_association.public`**

```hcl modules/network/main.tf
resource "aws_route_table" "public" {
  vpc_id = aws_vpc.this.id

  tags = merge(var.tags, { Name = "${var.name}-public" })
}

resource "aws_route" "public_internet" {
  route_table_id         = aws_route_table.public.id
  destination_cidr_block = "0.0.0.0/0"
  gateway_id             = aws_internet_gateway.this.id
}

resource "aws_route_table_association" "public" {
  count = var.az_count

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

- `resource "aws_route_table" "public"`: one table shared by all public subnets, because they all route the same way.
- `resource "aws_route" "public_internet"`: the default route.
  - `destination_cidr_block = "0.0.0.0/0"`: all traffic not matched by the implicit local VPC route.
  - `gateway_id = aws_internet_gateway.this.id`: sends it to the internet gateway, which gives the NAT gateways their path out.
- `resource "aws_route_table_association" "public"`: attaches the table to each public subnet (`count = var.az_count`, `subnet_id` by index). A subnet without an association uses the VPC main route table.

**Private routing — `aws_route_table.private`, `aws_route.private_nat`, `aws_route_table_association.private`**

```hcl modules/network/main.tf
# One private route table per AZ so each AZ egresses through its own NAT gateway.
resource "aws_route_table" "private" {
  count = var.az_count

  vpc_id = aws_vpc.this.id

  tags = merge(var.tags, { Name = "${var.name}-private-${local.azs[count.index]}" })
}

resource "aws_route" "private_nat" {
  count = var.az_count

  route_table_id         = aws_route_table.private[count.index].id
  destination_cidr_block = "0.0.0.0/0"
  nat_gateway_id         = aws_nat_gateway.this[var.single_nat_gateway ? 0 : count.index].id
}

resource "aws_route_table_association" "private" {
  count = var.az_count

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

- Comment: each AZ has its own route table so traffic can leave through that AZ's NAT gateway, avoiding cross-AZ data charges and a dependency on another AZ.
- `resource "aws_route_table" "private"`: `count = var.az_count`, with the AZ name in the Name tag.
- `resource "aws_route" "private_nat"`: the default route for each private table.
  - `route_table_id = aws_route_table.private[count.index].id`: the table of AZ N.
  - `destination_cidr_block = "0.0.0.0/0"`: all non-local traffic.
  - `nat_gateway_id = aws_nat_gateway.this[var.single_nat_gateway ? 0 : count.index].id`: with one gateway per AZ (default), table N targets gateway N. With `single_nat_gateway = true` only `aws_nat_gateway.this[0]` exists, so every table targets index 0. The tables stay one per AZ either way, so switching the flag changes only this route target, not the table layout. The index must be forced to 0 because `aws_nat_gateway.this[1]` would not exist.
- `resource "aws_route_table_association" "private"`: attaches table N to private subnet N.

**Data routing — `aws_route_table.data`, `aws_route_table_association.data`**

```hcl modules/network/main.tf
# Data tier: no 0.0.0.0/0 route. The only non-local route is the S3 endpoint prefix list.
resource "aws_route_table" "data" {
  vpc_id = aws_vpc.this.id

  tags = merge(var.tags, { Name = "${var.name}-data" })
}

resource "aws_route_table_association" "data" {
  count = var.az_count

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

- Comment: the data tier has no `0.0.0.0/0` route. Besides the implicit local route, the only other route is the one the S3 gateway endpoint adds (a prefix list route), so the database has no path to the internet.
- `resource "aws_route_table" "data"`: a single table, since no AZ-specific target is needed.
- `resource "aws_route_table_association" "data"`: attaches it to every data subnet by index.

**S3 gateway endpoint — `aws_vpc_endpoint.s3`**

```hcl modules/network/main.tf
# Gateway endpoint is free and keeps ECR image layer pulls (served from S3) off the NAT gateways.
resource "aws_vpc_endpoint" "s3" {
  vpc_id            = aws_vpc.this.id
  service_name      = "com.amazonaws.${local.region}.s3"
  vpc_endpoint_type = "Gateway"
  route_table_ids   = concat(aws_route_table.private[*].id, [aws_route_table.data.id])

  tags = merge(var.tags, { Name = "${var.name}-s3" })
}
```

- Comment: gateway endpoints cost nothing, and ECR serves image layers from S3, so pulls bypass the NAT gateways and their per-GB charge.
- `vpc_id`: the VPC the endpoint belongs to.
- `service_name = "com.amazonaws.${local.region}.s3"`: the regional S3 service. Built from the region lookup so the module works in any region.
- `vpc_endpoint_type = "Gateway"`: implemented as a route table entry rather than network interfaces.
- `route_table_ids = concat(aws_route_table.private[*].id, [aws_route_table.data.id])`: AWS adds a prefix list route to each listed table. The private tables use it for ECR layers; the data table gets it as its only non-local route. The public table is excluded because nothing there needs S3.
- `tags`: standard tags plus a Name tag.

**Interface endpoints — `aws_security_group.endpoints`, `aws_vpc_security_group_ingress_rule.endpoints_https`, `aws_vpc_endpoint.interface`**

```hcl modules/network/main.tf
resource "aws_security_group" "endpoints" {
  count = var.enable_interface_endpoints ? 1 : 0

  name        = "${var.name}-vpc-endpoints"
  description = "Interface VPC endpoints: HTTPS from inside the VPC"
  vpc_id      = aws_vpc.this.id

  tags = merge(var.tags, { Name = "${var.name}-vpc-endpoints" })
}

resource "aws_vpc_security_group_ingress_rule" "endpoints_https" {
  count = var.enable_interface_endpoints ? 1 : 0

  security_group_id = aws_security_group.endpoints[0].id
  description       = "HTTPS from the VPC"
  cidr_ipv4         = var.vpc_cidr
  ip_protocol       = "tcp"
  from_port         = 443
  to_port           = 443

  tags = var.tags
}

resource "aws_vpc_endpoint" "interface" {
  for_each = local.interface_endpoints

  vpc_id              = aws_vpc.this.id
  service_name        = "com.amazonaws.${local.region}.${each.key}"
  vpc_endpoint_type   = "Interface"
  subnet_ids          = aws_subnet.private[*].id
  security_group_ids  = [aws_security_group.endpoints[0].id]
  private_dns_enabled = true

  tags = merge(var.tags, { Name = "${var.name}-${replace(each.key, ".", "-")}" })
}
```

- `resource "aws_security_group" "endpoints"`: the firewall for the endpoint network interfaces.
  - `count = var.enable_interface_endpoints ? 1 : 0`: exists only when interface endpoints are enabled. The `[0]` references below are safe for the same reason.
  - `name`, `description`: names with the `var.name` prefix and states the purpose.
  - `vpc_id`: the VPC.
  - No inline rules: ingress is a separate resource, and with no egress rules declared the provider removes the default allow-all egress. Endpoints only answer requests, so that is enough.
  - `tags`: standard tags plus a Name tag.
- `resource "aws_vpc_security_group_ingress_rule" "endpoints_https"`: the one allowed inbound rule.
  - `count`: same toggle as the group.
  - `security_group_id = aws_security_group.endpoints[0].id`: the group above.
  - `description`: shown in the console.
  - `cidr_ipv4 = var.vpc_cidr`: any address in the VPC can call the endpoints.
  - `ip_protocol = "tcp"`, `from_port`/`to_port = 443`: HTTPS only, which is what AWS APIs use.
  - `tags = var.tags`: no Name tag; rules take the caller's tags only.
- `resource "aws_vpc_endpoint" "interface"`: one endpoint per service.
  - `for_each = local.interface_endpoints`: one per entry in the set (`ecr.api`, `ecr.dkr`, `logs`, `secretsmanager`), none when disabled. These let tasks call ECR (to authenticate and pull manifests), CloudWatch Logs and Secrets Manager without going through NAT.
  - `service_name = "com.amazonaws.${local.region}.${each.key}"`: the regional service for the current key.
  - `vpc_endpoint_type = "Interface"`: creates network interfaces with private IPs in the subnets.
  - `subnet_ids = aws_subnet.private[*].id`: one interface per AZ, in the private tier where the tasks run.
  - `security_group_ids = [aws_security_group.endpoints[0].id]`: restricts access to HTTPS from the VPC.
  - `private_dns_enabled = true`: the public service hostname resolves to the private endpoint IPs inside the VPC, so no client configuration changes. Requires the DNS settings enabled on the VPC.
  - `tags`: standard tags plus a Name tag, with dots in the key replaced by dashes (`ecr.api` becomes `ecr-api`).

**Flow log group — `aws_cloudwatch_log_group.flow`**

```hcl modules/network/main.tf
resource "aws_cloudwatch_log_group" "flow" {
  name              = "/aws/vpc/${var.name}-flow-logs"
  retention_in_days = var.flow_log_retention_days
  kms_key_id        = var.logs_kms_key_arn

  tags = merge(var.tags, { Name = "${var.name}-flow-logs" })
}
```

- `name = "/aws/vpc/${var.name}-flow-logs"`: a predictable path under the `/aws/` convention.
- `retention_in_days = var.flow_log_retention_days`: logs are deleted after this period (default 90). Without it the group keeps data forever and costs grow.
- `kms_key_id = var.logs_kms_key_arn`: encrypts the logs with the customer-managed key supplied by the caller. That key's policy must allow CloudWatch Logs to use it.
- `tags`: standard tags plus a Name tag.

**Flow log role — `aws_iam_policy_document.flow_assume`, `aws_iam_policy_document.flow_publish`, `aws_iam_role.flow`, `aws_iam_role_policy.flow`**

```hcl modules/network/main.tf
data "aws_iam_policy_document" "flow_assume" {
  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["vpc-flow-logs.amazonaws.com"]
    }

    # Confused-deputy protection recommended by the flow logs IAM docs.
    condition {
      test     = "StringEquals"
      variable = "aws:SourceAccount"
      values   = [local.account_id]
    }

    condition {
      test     = "ArnLike"
      variable = "aws:SourceArn"
      values   = ["arn:${local.partition}:ec2:${local.region}:${local.account_id}:vpc-flow-log/*"]
    }
  }
}

data "aws_iam_policy_document" "flow_publish" {
  statement {
    effect = "Allow"
    actions = [
      "logs:CreateLogStream",
      "logs:PutLogEvents",
      "logs:DescribeLogStreams",
    ]
    resources = [aws_cloudwatch_log_group.flow.arn, "${aws_cloudwatch_log_group.flow.arn}:*"]
  }
}

resource "aws_iam_role" "flow" {
  name               = "${var.name}-vpc-flow-logs"
  assume_role_policy = data.aws_iam_policy_document.flow_assume.json

  tags = var.tags
}

resource "aws_iam_role_policy" "flow" {
  name   = "${var.name}-vpc-flow-logs"
  role   = aws_iam_role.flow.id
  policy = data.aws_iam_policy_document.flow_publish.json
}
```

- `data "aws_iam_policy_document" "flow_assume"`: the trust policy, who may assume the role.
  - `effect = "Allow"`, `actions = ["sts:AssumeRole"]`: permits assuming the role.
  - `principals` with `type = "Service"`, `identifiers = ["vpc-flow-logs.amazonaws.com"]`: only the flow logs service can assume it.
  - `condition` `StringEquals` on `aws:SourceAccount` with `local.account_id`: the request must originate in this account.
  - `condition` `ArnLike` on `aws:SourceArn` with `arn:${local.partition}:ec2:${local.region}:${local.account_id}:vpc-flow-log/*`: it must come from a flow log resource in this account and region. Together the two conditions prevent a confused-deputy attack, where another account's flow log tricks the service into using this role.
- `data "aws_iam_policy_document" "flow_publish"`: the permissions policy.
  - `actions`: `logs:CreateLogStream`, `logs:PutLogEvents` and `logs:DescribeLogStreams`, the calls the service needs to write records.
  - `resources = [group ARN, "${group ARN}:*"]`: only the flow log group and its streams, not other log groups in the account.
- `resource "aws_iam_role" "flow"`: the role the service assumes.
  - `name`: prefixed with `var.name`.
  - `assume_role_policy`: the trust document above, rendered as JSON.
  - `tags = var.tags`: standard tags only.
- `resource "aws_iam_role_policy" "flow"`: attaches the permissions inline.
  - `name`: same as the role.
  - `role = aws_iam_role.flow.id`: the role it applies to.
  - `policy`: the publish document as JSON. Inline means the policy is deleted with the role.

**Flow log — `aws_flow_log.this`**

```hcl modules/network/main.tf
resource "aws_flow_log" "this" {
  vpc_id          = aws_vpc.this.id
  traffic_type    = "ALL"
  log_destination = aws_cloudwatch_log_group.flow.arn
  iam_role_arn    = aws_iam_role.flow.arn

  tags = merge(var.tags, { Name = "${var.name}-flow-log" })

  depends_on = [aws_iam_role_policy.flow]
}
```

- `vpc_id`: captures traffic for every network interface in the VPC.
- `traffic_type = "ALL"`: records accepted and rejected traffic. Rejected records show blocked attempts; accepted ones show what was allowed.
- `log_destination = aws_cloudwatch_log_group.flow.arn`: delivers to the encrypted log group. The default destination type is CloudWatch Logs, so no type argument is needed.
- `iam_role_arn`: the role the service assumes to write.
- `tags`: standard tags plus a Name tag.
- `depends_on = [aws_iam_role_policy.flow]`: the role has no attribute link to its permissions, so without this the flow log could be created before the policy exists and delivery would fail.

#### variables.tf

**Input validation — `vpc_cidr`, `az_count`**

```hcl modules/network/variables.tf
variable "vpc_cidr" {
  type        = string
  description = "IPv4 CIDR of the VPC. Must be between /16 and /20; subnet sizes scale with it."

  validation {
    condition     = can(cidrhost(var.vpc_cidr, 0)) && can(regex("^[0-9.]+/(1[6-9]|20)$", var.vpc_cidr))
    error_message = "vpc_cidr must be a valid IPv4 CIDR with a prefix length from /16 to /20."
  }
}

variable "az_count" {
  type        = number
  description = "Number of Availability Zones to span (2 or 3)."
  default     = 3

  validation {
    condition     = var.az_count >= 2 && var.az_count <= 3
    error_message = "az_count must be 2 or 3: fewer than 2 has no AZ redundancy, and the CIDR plan reserves room for 3."
  }
}
```

- `variable "vpc_cidr"` `validation`: rejects bad values at plan time, before any resource is created.
  - `can(cidrhost(var.vpc_cidr, 0))`: `cidrhost` errors on anything that is not a valid CIDR; `can` turns that error into `false`.
  - `can(regex("^[0-9.]+/(1[6-9]|20)$", var.vpc_cidr))`: restricts the prefix to /16 through /20. /16 is the largest VPC AWS allows; past /20 the 8-bit data and public tiers shrink below a useful size (a /24 VPC would give /32 subnets).
  - `error_message`: shown to the operator when either check fails.
- `variable "az_count"` `validation`: `>= 2 && <= 3`. One AZ has no redundancy, and the CIDR plan in `locals` reserves exactly three slots per tier, so four would collide with the next tier.

## Data

Aurora PostgreSQL 16.8 Serverless v2. RDS manages the master password, and storage is encrypted. IAM database authentication is on, `rds.force_ssl` is set, and the instances are pinned to different AZs. This module also creates an empty secret for the OpenAI key and owns the CPU and connection alarms.

| Inputs | Outputs |
|---|---|
| `name`, `tags`, `vpc_id`, `data_subnet_ids`, `db_name`, `instance_count`, `min_capacity`, `max_capacity`, `backup_retention_days`, `deletion_protection`, `alarm_topic_arn`, `logs_kms_key_arn` optional | `db_endpoint`, `db_reader_endpoint`, `db_port`, `db_name`, `db_security_group_id`, `db_master_secret_arn`, `openai_secret_arn`, `kms_key_arn` |

### Walkthrough

#### main.tf

**Lookups and locals — `data.aws_subnet.data`, `local.*`**

```hcl modules/data/main.tf
data "aws_caller_identity" "current" {}
data "aws_partition" "current" {}

data "aws_subnet" "data" {
  count = length(var.data_subnet_ids)
  id    = var.data_subnet_ids[count.index]
}

locals {
  cluster_identifier = "${var.name}-db"

  # Aurora PostgreSQL 16.8 is an LTS release (standard support to 2029-02-28) and supports Serverless v2.
  # Source: AWS Aurora PostgreSQL release calendar.
  engine_version = "16.8"

  # Sorted distinct AZs of the data subnets. Each instance is pinned to one of them, so the
  # cluster's availability_zones argument is left unset (setting fewer than 3 forces replacement).
  azs = sort(distinct(data.aws_subnet.data[*].availability_zone))

  # Alarm thresholds are starting values; tune them from observed load.
  cpu_alarm_threshold         = 80
  connections_alarm_threshold = 200
}
```

- `data "aws_caller_identity" "current"`: reads the account ID of the credentials Terraform runs with, so the key policy can name this account without a variable.
- `data "aws_partition" "current"`: reads the partition (`aws`, `aws-cn`, `aws-us-gov`) so ARNs built by hand are not hard-coded to `arn:aws:`.
- `data "aws_subnet" "data"`: looks up each data subnet so the module can read its availability zone. The network module only outputs IDs.
  - `count = length(var.data_subnet_ids)`: one lookup per subnet ID.
  - `id = var.data_subnet_ids[count.index]`: the subnet this instance of the lookup reads.
- `cluster_identifier = "${var.name}-db"`: the cluster name, kept in a local because the log group path, the final snapshot name and the cluster itself all derive from it.
- `engine_version = "16.8"`: pins Aurora PostgreSQL to a long-term-support release that supports Serverless v2. A pinned version keeps plans stable; the parameter group family is derived from it.
- `azs = sort(distinct(data.aws_subnet.data[*].availability_zone))`: the AZs of the data subnets, deduplicated and sorted so the order is stable between plans. Instances are pinned to these (see the instance snippet), so the cluster's `availability_zones` argument stays unset. Setting fewer than 3 would force replacement of the cluster.
- `cpu_alarm_threshold = 80` and `connections_alarm_threshold = 200`: alarm thresholds held in locals so the alarm description and the threshold cannot drift apart. They are starting values to tune from observed load.

**Data key — `aws_iam_policy_document.key`, `aws_kms_key.data`, `aws_kms_alias.data`**

```hcl modules/data/main.tf
# One customer-managed key for cluster storage, the RDS-managed master secret, the OpenAI secret and Performance Insights.
data "aws_iam_policy_document" "key" {
  # Standard statement: delegates key use to IAM policies in this account.
  statement {
    sid       = "EnableIamPolicies"
    actions   = ["kms:*"]
    resources = ["*"]

    principals {
      type        = "AWS"
      identifiers = ["arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:root"]
    }
  }
}

resource "aws_kms_key" "data" {
  description             = "${var.name} database, database secrets and OpenAI key secret"
  enable_key_rotation     = true
  deletion_window_in_days = 30
  policy                  = data.aws_iam_policy_document.key.json
  tags                    = var.tags
}

resource "aws_kms_alias" "data" {
  name          = "alias/${var.name}-data"
  target_key_id = aws_kms_key.data.key_id
}
```

- `data "aws_iam_policy_document" "key"`: builds the key policy as JSON from HCL, which avoids hand-written JSON.
  - `sid = "EnableIamPolicies"`: names the statement.
  - `actions = ["kms:*"]` and `resources = ["*"]`: all KMS actions. In a key policy `*` means this key only.
  - `principals { type = "AWS" ... }`: the account root. Granting the root principal is what lets IAM policies in this account grant access to the key. Without this statement only the policy itself controls access and the key can become unmanageable.
  - `identifiers = ["arn:${...partition}:iam::${...account_id}:root"]`: the root ARN built from the two lookups above.
- `resource "aws_kms_key" "data"`: one customer-managed key for the cluster storage, the RDS-managed master secret, the OpenAI secret and Performance Insights. One key keeps access control in one place.
  - `description`: shown in the KMS console so the key's use is clear.
  - `enable_key_rotation = true`: AWS rotates the key material every year. Existing data stays readable.
  - `deletion_window_in_days = 30`: the longest waiting period before a scheduled deletion takes effect, which leaves time to cancel an accidental deletion of a key that protects the database.
  - `policy = data.aws_iam_policy_document.key.json`: attaches the policy above.
  - `tags = var.tags`: standard tags from the caller, applied to every taggable resource in this module.
- `resource "aws_kms_alias" "data"`: a readable handle for the key.
  - `name = "alias/${var.name}-data"`: aliases must start with `alias/`; the `${var.name}-...` pattern keeps names unique per environment.
  - `target_key_id = aws_kms_key.data.key_id`: points the alias at the key.

**Subnet group — `aws_db_subnet_group.this`**

```hcl modules/data/main.tf
resource "aws_db_subnet_group" "this" {
  name       = "${var.name}-db"
  subnet_ids = var.data_subnet_ids
  tags       = var.tags
}
```

- `name = "${var.name}-db"`: the group name, following the `${var.name}-<purpose>` convention.
- `subnet_ids = var.data_subnet_ids`: the subnets Aurora may place instances in. They are the network module's isolated data subnets, so the database has no internet route. RDS requires subnets in at least two AZs.
- `tags = var.tags`: standard tags.

**Database security group — `aws_security_group.db`**

```hcl modules/data/main.tf
# No ingress rule here: the service module adds the task-to-database rule.
resource "aws_security_group" "db" {
  name        = "${var.name}-db"
  description = "Aurora cluster for ${var.name}; ingress rules are added by consumers"
  vpc_id      = var.vpc_id
  tags        = merge(var.tags, { Name = "${var.name}-db" })

  lifecycle {
    create_before_destroy = true
  }
}
```

- `name` and `description`: the description records that consumers add the ingress rules.
- `vpc_id = var.vpc_id`: the group belongs to the VPC that holds the database.
- `tags = merge(var.tags, { Name = "${var.name}-db" })`: standard tags plus a `Name` tag, which the console uses as the display name.
- No `ingress` or `egress` blocks: the group is created with no ingress, so nothing can reach the database until the service module adds the task-to-database rule. The group ID is exported as `db_security_group_id`, which keeps this module free of knowledge about who connects.
- `lifecycle { create_before_destroy = true }`: a security group name change forces replacement, and a group still attached to the cluster cannot be deleted. Creating the new group first lets the cluster move to it before the old one is removed.

**Cluster parameter group — `aws_rds_cluster_parameter_group.this`**

```hcl modules/data/main.tf
resource "aws_rds_cluster_parameter_group" "this" {
  name        = "${var.name}-db"
  family      = "aurora-postgresql${split(".", local.engine_version)[0]}"
  description = "${var.name} cluster parameters"
  tags        = var.tags

  # Reject any connection that is not TLS.
  parameter {
    name  = "rds.force_ssl"
    value = "1"
  }
}
```

- `name`: follows the `${var.name}-db` naming.
- `family = "aurora-postgresql${split(".", local.engine_version)[0]}"`: the family must match the engine's major version (`aurora-postgresql16`). Deriving it from `local.engine_version` means a version bump cannot leave the two out of step.
- `description`: free text shown in the console.
- `tags = var.tags`: standard tags.
- `parameter { name = "rds.force_ssl", value = "1" }`: the server rejects any connection that is not TLS, so clients cannot send traffic or credentials in clear text inside the VPC.

**PostgreSQL log group — `aws_cloudwatch_log_group.postgresql`**

```hcl modules/data/main.tf
# Pre-created so the log group uses the logs key; RDS would otherwise create it with default encryption.
# Unconditional on purpose: a count on logs_kms_key_arn would be unknown on the first plan.
resource "aws_cloudwatch_log_group" "postgresql" {
  name              = "/aws/rds/cluster/${local.cluster_identifier}/postgresql"
  retention_in_days = 90
  kms_key_id        = var.logs_kms_key_arn
  tags              = var.tags
}
```

- `name = "/aws/rds/cluster/${local.cluster_identifier}/postgresql"`: the exact path RDS writes the `postgresql` log export to. Creating the group first with this name means RDS uses it rather than creating its own.
- `retention_in_days = 90`: logs expire after 90 days instead of accumulating forever.
- `kms_key_id = var.logs_kms_key_arn`: encrypts the group with the observability module's logs key. If RDS created the group it would use default encryption. When the variable is null, the group uses CloudWatch Logs default encryption.
- No `count` on `var.logs_kms_key_arn`: the key ARN is unknown on the first plan, and a `count` that depends on it would fail. The group is therefore always created.
- `tags = var.tags`: standard tags.

**Aurora cluster — `aws_rds_cluster.this`**

```hcl modules/data/main.tf
resource "aws_rds_cluster" "this" {
  cluster_identifier = local.cluster_identifier
  engine             = "aurora-postgresql"
  engine_mode        = "provisioned"
  engine_version     = local.engine_version
  database_name      = var.db_name
  master_username    = "patent_admin"

  # RDS creates and rotates the master password in Secrets Manager; it never appears in Terraform state.
  manage_master_user_password   = true
  master_user_secret_kms_key_id = aws_kms_key.data.arn

  storage_encrypted                   = true
  kms_key_id                          = aws_kms_key.data.arn
  iam_database_authentication_enabled = true

  db_subnet_group_name            = aws_db_subnet_group.this.name
  db_cluster_parameter_group_name = aws_rds_cluster_parameter_group.this.name
  vpc_security_group_ids          = [aws_security_group.db.id]

  backup_retention_period = var.backup_retention_days
  copy_tags_to_snapshot   = true
  deletion_protection     = var.deletion_protection

  # A final snapshot is only skipped when deletion protection is off (disposable environments).
  skip_final_snapshot       = !var.deletion_protection
  final_snapshot_identifier = var.deletion_protection ? "${local.cluster_identifier}-final" : null

  enabled_cloudwatch_logs_exports = ["postgresql"]

  serverlessv2_scaling_configuration {
    min_capacity = var.min_capacity
    max_capacity = var.max_capacity
  }

  tags = var.tags

  depends_on = [aws_cloudwatch_log_group.postgresql]
}
```

- `cluster_identifier = local.cluster_identifier`: the cluster name.
- `engine = "aurora-postgresql"`: Aurora with PostgreSQL compatibility.
- `engine_mode = "provisioned"`: the mode that Serverless v2 uses. Serverless v2 capacity comes from the scaling block and the `db.serverless` instance class, not from a separate engine mode.
- `engine_version = local.engine_version`: the pinned version.
- `database_name = var.db_name`: creates the initial database on the cluster.
- `master_username = "patent_admin"`: the admin user.
- `manage_master_user_password = true`: RDS generates the master password, stores it in Secrets Manager and rotates it. The password never appears in Terraform state or code.
- `master_user_secret_kms_key_id = aws_kms_key.data.arn`: encrypts that secret with the data key rather than the AWS-managed `aws/secretsmanager` key, so access follows this module's key policy.
- `storage_encrypted = true` and `kms_key_id = aws_kms_key.data.arn`: encrypts storage, snapshots and backups at rest with the data key. Encryption cannot be added to an existing cluster without a restore.
- `iam_database_authentication_enabled = true`: lets clients log in with short-lived IAM tokens instead of the password. It does not grant any access by itself.
- `db_subnet_group_name`: places the cluster in the data subnets.
- `db_cluster_parameter_group_name`: applies the TLS-only parameter group.
- `vpc_security_group_ids = [aws_security_group.db.id]`: attaches the security group with no ingress rule.
- `backup_retention_period = var.backup_retention_days`: days of automated backups (and point-in-time restore window).
- `copy_tags_to_snapshot = true`: snapshots inherit the cluster's tags, so cost and ownership tags survive.
- `deletion_protection = var.deletion_protection`: blocks deletion of the cluster while true. Staging and prod set it to `true`; dev sets it to `false`.
- `skip_final_snapshot = !var.deletion_protection`: a final snapshot is skipped only when protection is off, which marks the environment as disposable.
- `final_snapshot_identifier = var.deletion_protection ? "${local.cluster_identifier}-final" : null`: names the snapshot taken at destroy when protection is on. RDS requires a name if the snapshot is not skipped, and it must not be set when it is skipped.
- `enabled_cloudwatch_logs_exports = ["postgresql"]`: ships the PostgreSQL log to CloudWatch Logs, into the group created above.
- `serverlessv2_scaling_configuration`: sets the Serverless v2 range for every instance in the cluster.
  - `min_capacity = var.min_capacity`: the floor in ACUs. A low floor reduces idle cost.
  - `max_capacity = var.max_capacity`: the ceiling in ACUs. It caps cost and the largest load the database can absorb.
- `tags = var.tags`: standard tags.
- `depends_on = [aws_cloudwatch_log_group.postgresql]`: no attribute of the log group is referenced, so Terraform would not otherwise order them. The group must exist before the cluster starts exporting logs, or RDS would create its own.

**Cluster instances — `aws_rds_cluster_instance.this`**

```hcl modules/data/main.tf
resource "aws_rds_cluster_instance" "this" {
  count = var.instance_count

  identifier         = "${var.name}-db-${count.index + 1}"
  cluster_identifier = aws_rds_cluster.this.id
  instance_class     = "db.serverless"
  engine             = aws_rds_cluster.this.engine
  engine_version     = aws_rds_cluster.this.engine_version

  # Spread instances over the data-subnet AZs; wraps around if there are more instances than AZs.
  availability_zone    = element(local.azs, count.index)
  db_subnet_group_name = aws_db_subnet_group.this.name
  publicly_accessible  = false

  # Lower tiers fail over first, so the writer's replacement is deterministic.
  promotion_tier = min(count.index, 15)

  performance_insights_enabled    = true
  performance_insights_kms_key_id = aws_kms_key.data.arn

  tags = var.tags
}
```

- `count = var.instance_count`: one resource per instance. The first is the initial writer, the rest are readers. Aurora can elect a different writer on failover.
- `identifier = "${var.name}-db-${count.index + 1}"`: names instances `-db-1`, `-db-2`, and so on, counting from 1.
- `cluster_identifier = aws_rds_cluster.this.id`: joins the instance to the cluster.
- `instance_class = "db.serverless"`: the class that makes the instance scale within the cluster's ACU range.
- `engine` and `engine_version`: read from the cluster so the instance cannot disagree with it.
- `availability_zone = element(local.azs, count.index)`: pins each instance to a data-subnet AZ. `element` wraps around, so more instances than AZs still works. Separate AZs mean one AZ outage leaves a reader to promote.
- `db_subnet_group_name`: the same subnet group as the cluster.
- `publicly_accessible = false`: no public IP, regardless of subnet routing.
- `promotion_tier = min(count.index, 15)`: failover priority; lower tiers are promoted first, so the replacement writer is deterministic. Aurora's tiers go from 0 to 15, hence the `min`.
- `performance_insights_enabled = true` and `performance_insights_kms_key_id = aws_kms_key.data.arn`: turns on Performance Insights and encrypts its data with the data key.
- `tags = var.tags`: standard tags.

**OpenAI key secret — `aws_secretsmanager_secret.openai`**

```hcl modules/data/main.tf
# Container only: the key value is set out of band so it never reaches Terraform state.
resource "aws_secretsmanager_secret" "openai" {
  name        = "${var.name}/openai-api-key"
  description = "OpenAI API key for ${var.name}; value is set manually"
  kms_key_id  = aws_kms_key.data.arn
  tags        = var.tags
}
```

- `name = "${var.name}/openai-api-key"`: the secret path, namespaced by environment.
- `description`: states that the value is set manually.
- `kms_key_id = aws_kms_key.data.arn`: encrypts the value with the data key.
- No `aws_secretsmanager_secret_version`: the resource is a container only. The key value is put in by hand, so it never appears in Terraform state or code. Until then the service has an empty secret to read.
- `tags = var.tags`: standard tags.

**CPU alarm — `aws_cloudwatch_metric_alarm.cpu`**

```hcl modules/data/main.tf
resource "aws_cloudwatch_metric_alarm" "cpu" {
  alarm_name          = "${var.name}-db-cpu-high"
  alarm_description   = "Aurora cluster CPU above ${local.cpu_alarm_threshold}%"
  namespace           = "AWS/RDS"
  metric_name         = "CPUUtilization"
  statistic           = "Average"
  period              = 300
  evaluation_periods  = 3
  threshold           = local.cpu_alarm_threshold
  comparison_operator = "GreaterThanOrEqualToThreshold"
  # Missing data means the cluster is not reporting, which is itself a problem.
  treat_missing_data = "breaching"
  alarm_actions      = [var.alarm_topic_arn]
  ok_actions         = [var.alarm_topic_arn]
  tags               = var.tags

  dimensions = {
    DBClusterIdentifier = aws_rds_cluster.this.cluster_identifier
  }
}
```

- `alarm_name = "${var.name}-db-cpu-high"` and `alarm_description`: the name and a description that includes the threshold from the local.
- `namespace = "AWS/RDS"` and `metric_name = "CPUUtilization"`: the RDS CPU metric.
- `statistic = "Average"`: averages samples in each period, so a short spike does not alarm.
- `period = 300` and `evaluation_periods = 3`: three consecutive 5-minute periods, so CPU must stay high for 15 minutes.
- `threshold = local.cpu_alarm_threshold` and `comparison_operator = "GreaterThanOrEqualToThreshold"`: the alarm fires at 80 percent or more.
- `treat_missing_data = "breaching"`: no data counts as a breach. A cluster that stops reporting is itself a problem, and the default would hide it.
- `alarm_actions = [var.alarm_topic_arn]`: notifies the observability module's SNS topic when the alarm fires.
- `ok_actions = [var.alarm_topic_arn]`: notifies the same topic on recovery.
- `tags = var.tags`: standard tags.
- `dimensions = { DBClusterIdentifier = ... }`: scopes the metric to this cluster rather than every instance in the account.

**Connections alarm — `aws_cloudwatch_metric_alarm.connections`**

```hcl modules/data/main.tf
resource "aws_cloudwatch_metric_alarm" "connections" {
  alarm_name          = "${var.name}-db-connections-high"
  alarm_description   = "Aurora cluster connections above ${local.connections_alarm_threshold}"
  namespace           = "AWS/RDS"
  metric_name         = "DatabaseConnections"
  statistic           = "Average"
  period              = 300
  evaluation_periods  = 3
  threshold           = local.connections_alarm_threshold
  comparison_operator = "GreaterThanOrEqualToThreshold"
  treat_missing_data  = "breaching"
  alarm_actions       = [var.alarm_topic_arn]
  ok_actions          = [var.alarm_topic_arn]
  tags                = var.tags

  dimensions = {
    DBClusterIdentifier = aws_rds_cluster.this.cluster_identifier
  }
}
```

Same shape as the CPU alarm; only the differences are listed.

- `alarm_name`, `alarm_description`: `${var.name}-db-connections-high`, with the threshold from the local.
- `metric_name = "DatabaseConnections"`: the number of client connections. Connection exhaustion fails requests even when CPU is low.
- `threshold = local.connections_alarm_threshold`: 200. Starting value; tune it against observed load.
- `period`, `evaluation_periods`, `statistic`, `comparison_operator`: as in the CPU alarm.
- `treat_missing_data = "breaching"`, `alarm_actions`, `ok_actions`, `tags`, `dimensions`: as in the CPU alarm.

#### variables.tf

**Instance count validation — `variable.instance_count`**

```hcl modules/data/variables.tf
variable "instance_count" {
  type        = number
  description = "Number of Aurora instances (1 writer plus readers), each placed in a different AZ where possible."
  default     = 2

  validation {
    condition     = var.instance_count >= 1
    error_message = "instance_count must be at least 1."
  }
}
```

- `default = 2`: one writer and one reader.
- `validation { condition = var.instance_count >= 1 }`: a cluster without instances has no writer. The check fails at plan time with the given message instead of producing a cluster nobody can connect to.

#### outputs.tf

**Master secret output — `output.db_master_secret_arn`**

```hcl modules/data/outputs.tf
output "db_master_secret_arn" {
  description = "Secret that RDS manages for the master user."
  value       = aws_rds_cluster.this.master_user_secret[0].secret_arn
}
```

- `aws_rds_cluster.this.master_user_secret[0].secret_arn`: the attribute is a list because RDS exposes it as a block that exists only when `manage_master_user_password` is true; `[0]` takes the single entry. Consumers use the ARN to read the password from Secrets Manager.

## Service

- **Images:** an ECR repository with immutable tags and scan on push.
- **Load balancer:** an internal ALB with an HTTPS listener, accepting traffic only from CloudFront.
- **Tasks:** a Fargate service with a read-only root file system. Secrets are injected from Secrets Manager. Each task also runs an OpenTelemetry Collector sidecar (`otel-collector`) that sends metrics to CloudWatch and traces to X-Ray.
- **Deploys and scaling:** rolling deploys with a circuit breaker and an alarm rollback, and autoscaling on CPU and on requests per target.
- **Alarms:** the 5xx ratio and the AI suggestion failure ratio (both also trigger deploy rollback), unhealthy hosts, and p95 response time.

| Inputs | Outputs |
|---|---|
| `name`, `tags`, `vpc_id`, `private_subnet_ids`, `domain_name`, `route53_zone_id`, `container_port`, `health_check_path`, `image_tag`, `cpu`, `memory`, `min_tasks`, `max_tasks`, `use_fargate_spot`, `openai_model`, `openai_secret_arn`, `db_master_secret_arn`, `db_host`, `db_name`, `db_port`, `db_security_group_id`, `secrets_kms_key_arn`, `logs_kms_key_arn`, `log_retention_days`, `alarm_topic_arn`, `environment`, `trace_sample_ratio` | `alb_arn`, `alb_dns_name`, `alb_arn_suffix`, `target_group_arn_suffix`, `ecs_cluster_name`, `ecs_service_name`, `task_definition_family`, `task_execution_role_arn`, `task_role_arn`, `task_security_group_id`, `ecr_repository_url`, `log_group_name`, `rollback_alarm_names` |

:::note[Idle timeout]
The ALB idle timeout is 600 seconds. This matches CloudFront's fixed 10-minute WebSocket idle timeout, so neither hop drops an editor session the other still considers live.
:::

### Walkthrough

#### main.tf

**Lookups and locals**

```hcl modules/service/main.tf
data "aws_caller_identity" "current" {}
data "aws_partition" "current" {}
data "aws_region" "current" {}

locals {
  container_name = "server"

  # Starting value: ALB idle timeout, in seconds. It also bounds an idle WebSocket,
  # because the ALB closes a connection after this long without data in either direction.
  # The editor sends debounced messages, so a session can sit quiet for minutes. The default
  # of 60 would drop live editor sessions. 600 matches CloudFront's fixed 10-minute WebSocket
  # idle timeout, so neither hop closes a connection the other still considers live.
  alb_idle_timeout_seconds = 600

  # Starting values for target-tracking autoscaling. Tune them from load tests.
  autoscaling_cpu_target_percent         = 60
  autoscaling_requests_per_target        = 500
  autoscaling_scale_out_cooldown_seconds = 60
  autoscaling_scale_in_cooldown_seconds  = 300
  health_check_grace_period_seconds      = 60
  alb_deregistration_delay_seconds       = 60
  ecr_keep_last_images                   = 30
  ecr_expire_untagged_after_days         = 7
  ecs_task_stop_timeout_seconds          = 120

  # OpenTelemetry collector sidecar (AWS Distro for OpenTelemetry), pinned by index digest. It comes
  # from public ECR, so a task start pulls it through the NAT gateway. ADOT is the AWS-supported
  # build and contains the awsemf and awsxray exporters.
  otel_collector_image = "public.ecr.aws/aws-observability/aws-otel-collector:v0.51.0@sha256:955e240b27d7fd3c7995fd937db4b963975948eb553f656d8c37a564e5b5e07d"
  # The image already runs as this user (uid 4317). Set explicitly so a change of the image cannot make it root.
  otel_collector_user = "4317"
  # Starting values for the sidecar, not measured. The server gets the rest of the task, so the
  # containers add up to var.cpu and var.memory exactly. memory is a hard limit: the kernel kills
  # the collector alone, never the server, and memory_limiter in aws.yaml stays below it.
  otel_collector_cpu        = 64
  otel_collector_memory_mib = 256

  # The collector config is one file for every environment, kept with the other collector configs.
  # It reaches the task as the AOT_CONFIG_CONTENT environment variable.
  otel_collector_config = file("${path.module}/../../../observability/collector/aws.yaml")
}
```

- `data "aws_caller_identity" "current"`: reads the account ID of the credentials Terraform runs with, so policies can name this account without a variable.
- `data "aws_partition" "current"`: reads the partition (`aws`, `aws-cn`, `aws-us-gov`) so ARNs built by string interpolation are not hardcoded to `aws`.
- `data "aws_region" "current"`: reads the region the provider targets, used for the log driver region.
- `container_name = "server"`: one name shared by the container definition and the service's `load_balancer` block. They must match exactly, so it lives in one place.
- `alb_idle_timeout_seconds = 600`: the ALB closes a connection after this long without data in either direction, which also ends an idle WebSocket. The editor sends debounced messages, so a session can sit quiet for minutes and the default of 60 would drop live sessions. 600 equals CloudFront's fixed WebSocket idle timeout, so neither hop closes a connection the other still considers live.
- `autoscaling_cpu_target_percent = 60`: average CPU the CPU policy holds. It leaves headroom for load that arrives while new tasks start.
- `autoscaling_requests_per_target = 500`: requests per target per minute that the request-count policy holds.
- `autoscaling_scale_out_cooldown_seconds = 60` and `autoscaling_scale_in_cooldown_seconds = 300`: scale out quickly, scale in slowly, so a brief dip does not remove capacity that is needed again a minute later.
- `health_check_grace_period_seconds = 60`: how long ECS ignores failed ALB health checks for a new task, so a slow-starting container is not killed before it is ready.
- `alb_deregistration_delay_seconds = 60`: how long the ALB keeps a draining target before removing it.
- `ecr_keep_last_images = 30` and `ecr_expire_untagged_after_days = 7`: retention values for the ECR lifecycle policy.
- `ecs_task_stop_timeout_seconds = 120`: grace time between SIGTERM and SIGKILL for the container.
- `otel_collector_image`: the AWS Distro for OpenTelemetry collector, pinned by digest so a task start always runs the same build. It contains the `awsemf` and `awsxray` exporters. Public ECR means the pull goes through the NAT.
- `otel_collector_user = "4317"`: the image's own non-root user, set explicitly so an image change cannot run the collector as root.
- `otel_collector_cpu = 64` and `otel_collector_memory_mib = 256`: the sidecar's share of the task. The server container gets the rest, so the two add up to the task size exactly. Memory is a hard limit, so the kernel kills only the collector if it grows, never the server.
- `otel_collector_config = file(...)`: reads `observability/collector/aws.yaml`, which sits outside `infrastructure/` with the other collector configs. Because Terraform reads it, a change to that file triggers the Terraform CI job and plans (`scripts/ci/changed-paths.sh`, `terraform.yml`).
- The comments mark these as starting values to tune from load tests. Keeping them as locals gives each magic number a name and one definition site.

#### ecr.tf

**Image repository — `aws_ecr_repository.server`**

```hcl modules/service/ecr.tf
resource "aws_ecr_repository" "server" {
  name = "${var.name}-server"
  # Immutable tags make a deployed tag always mean the same image, so rollback is exact.
  image_tag_mutability = "IMMUTABLE"

  image_scanning_configuration {
    scan_on_push = true
  }

  # Customer-managed key, same rule as every other data store.
  encryption_configuration {
    encryption_type = "KMS"
    kms_key         = var.secrets_kms_key_arn
  }

  tags = var.tags
}
```

- `name = "${var.name}-server"`: the repository name carries the deployment prefix, so several deployments can share an account and region.
- `image_tag_mutability = "IMMUTABLE"`: a tag can be pushed once. A deployed tag always names the same image, so rolling back to a previous tag restores exactly what ran before.
- `image_scanning_configuration { scan_on_push = true }`: ECR scans each pushed image for known vulnerabilities, with no separate scanner to run.
- `encryption_configuration`: encrypts images at rest.
  - `encryption_type = "KMS"`: use a KMS key instead of the default AES-256 service-owned key.
  - `kms_key = var.secrets_kms_key_arn`: the customer-managed key from the data module, the same rule as every other data store.
- `tags = var.tags`: standard tags passed in by the caller. Nearly every taggable resource in this module sets them, so cost and ownership reports cover all of it.

**Image retention — `aws_ecr_lifecycle_policy.server`**

```hcl modules/service/ecr.tf
resource "aws_ecr_lifecycle_policy" "server" {
  repository = aws_ecr_repository.server.name

  policy = jsonencode({
    rules = [
      {
        rulePriority = 1
        description  = "Expire untagged images"
        selection = {
          tagStatus   = "untagged"
          countType   = "sinceImagePushed"
          countUnit   = "days"
          countNumber = local.ecr_expire_untagged_after_days
        }
        action = { type = "expire" }
      },
      {
        # The catch-all rule must have the highest priority number.
        rulePriority = 2
        description  = "Keep the newest ${local.ecr_keep_last_images} images"
        selection = {
          tagStatus   = "any"
          countType   = "imageCountMoreThan"
          countNumber = local.ecr_keep_last_images
        }
        action = { type = "expire" }
      },
    ]
  })
}
```

- `repository = aws_ecr_repository.server.name`: attaches the policy to the repository above.
- `policy = jsonencode({ rules = [...] })`: ECR takes the policy as a JSON string. `jsonencode` builds it from HCL, which avoids quoting mistakes and lets the rules read the locals.
- Rule 1, `rulePriority = 1`: rules are evaluated in priority order.
  - `description = "Expire untagged images"`: a human label shown in the console.
  - `tagStatus = "untagged"`: matches only images with no tag, such as layers orphaned when a tag moves.
  - `countType = "sinceImagePushed"`, `countUnit = "days"`, `countNumber = local.ecr_expire_untagged_after_days`: match untagged images pushed more than 7 days ago.
  - `action = { type = "expire" }`: delete the matches.
- Rule 2, `rulePriority = 2`: ECR requires the rule with `tagStatus = "any"` to have the highest priority number, so it runs last.
  - `description = "Keep the newest ${local.ecr_keep_last_images} images"`: the label interpolates the local so it cannot drift from the value.
  - `tagStatus = "any"`: matches every remaining image, tagged or not.
  - `countType = "imageCountMoreThan"` and `countNumber = local.ecr_keep_last_images`: match images beyond the newest 30. This caps storage cost and still leaves enough tags to roll back to.
  - `action = { type = "expire" }`: delete the matches.

#### iam.tf

**Shared trust policy — `aws_iam_policy_document.ecs_tasks_assume`**

```hcl modules/service/iam.tf
data "aws_iam_policy_document" "ecs_tasks_assume" {
  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["ecs-tasks.amazonaws.com"]
    }

    # Confused-deputy protection: only ECS tasks of this account may assume the roles.
    condition {
      test     = "StringEquals"
      variable = "aws:SourceAccount"
      values   = [data.aws_caller_identity.current.account_id]
    }
  }
}
```

- `data "aws_iam_policy_document" "ecs_tasks_assume"`: builds the trust policy as HCL instead of a JSON string. Both task roles reuse it.
- `effect = "Allow"` and `actions = ["sts:AssumeRole"]`: permit the listed principal to assume the role.
- `principals { type = "Service", identifiers = ["ecs-tasks.amazonaws.com"] }`: the principal is the ECS tasks service, so only ECS can hand these roles to a container.
- `condition`: the confused-deputy guard.
  - `test = "StringEquals"` and `variable = "aws:SourceAccount"`: require the request to originate from a named account.
  - `values = [data.aws_caller_identity.current.account_id]`: this account. Without it, an ECS task in another account could be tricked into assuming a role here.

**Task execution role — `aws_iam_role.task_execution` and managed policy**

```hcl modules/service/iam.tf
resource "aws_iam_role" "task_execution" {
  name               = "${var.name}-task-execution"
  assume_role_policy = data.aws_iam_policy_document.ecs_tasks_assume.json
  tags               = var.tags
}

# ECR image pull and log delivery.
resource "aws_iam_role_policy_attachment" "task_execution_managed" {
  role       = aws_iam_role.task_execution.name
  policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}
```

- `resource "aws_iam_role" "task_execution"`: the role ECS itself uses to start the task, as opposed to the role the application code runs as.
  - `name = "${var.name}-task-execution"`: deployment prefix plus purpose. This naming pattern repeats on every named resource in the module.
  - `assume_role_policy = data.aws_iam_policy_document.ecs_tasks_assume.json`: the shared trust policy.
  - `tags = var.tags`: standard tags.
- `resource "aws_iam_role_policy_attachment" "task_execution_managed"`: attaches the AWS managed policy for task execution.
  - `role = aws_iam_role.task_execution.name`: the role to attach to.
  - `policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"`: grants ECR image pull and CloudWatch Logs delivery. The partition lookup keeps the ARN valid outside the `aws` partition.

**Secret read access — `aws_iam_policy_document.task_execution_secrets`**

```hcl modules/service/iam.tf
data "aws_iam_policy_document" "task_execution_secrets" {
  statement {
    sid       = "ReadTaskSecrets"
    effect    = "Allow"
    actions   = ["secretsmanager:GetSecretValue"]
    resources = [var.openai_secret_arn, var.db_master_secret_arn]
  }

  statement {
    sid       = "DecryptTaskSecrets"
    effect    = "Allow"
    actions   = ["kms:Decrypt"]
    resources = [var.secrets_kms_key_arn]
  }
}

resource "aws_iam_role_policy" "task_execution_secrets" {
  name   = "${var.name}-task-execution-secrets"
  role   = aws_iam_role.task_execution.id
  policy = data.aws_iam_policy_document.task_execution_secrets.json
}
```

- `data "aws_iam_policy_document" "task_execution_secrets"`: an inline policy for what the managed policy does not cover, reading the secrets injected into the container.
- `statement "ReadTaskSecrets"`: `sid` names the statement in audit output.
  - `effect = "Allow"` and `actions = ["secretsmanager:GetSecretValue"]`: read secret values only. No list, describe or write actions.
  - `resources = [var.openai_secret_arn, var.db_master_secret_arn]`: exactly the two secrets the container definition references, not `*`.
- `statement "DecryptTaskSecrets"`:
  - `actions = ["kms:Decrypt"]`: Secrets Manager returns the value only if the caller can decrypt it with the secret's key.
  - `resources = [var.secrets_kms_key_arn]`: only the secrets key from the data module.
- `resource "aws_iam_role_policy" "task_execution_secrets"`: attaches the document to the execution role.
  - `name = "${var.name}-task-execution-secrets"`: inline policy name.
  - `role = aws_iam_role.task_execution.id`: the execution role, not the task role. ECS resolves `secrets` before the container starts, so the application never needs this permission.
  - `policy = data.aws_iam_policy_document.task_execution_secrets.json`: the rendered JSON.

**Task role and its telemetry policy — `aws_iam_role.task`, `aws_iam_role_policy.task_telemetry`**

```hcl modules/service/iam.tf
# The application calls no AWS API. The task role is for the collector sidecar in the same task:
# the two exporters in observability/collector/aws.yaml need exactly the actions below. ECS gives
# one task role to every container of the task, so the server can use them too. They only allow
# writing telemetry, nothing that reads data.
resource "aws_iam_role" "task" {
  name               = "${var.name}-task"
  assume_role_policy = data.aws_iam_policy_document.ecs_tasks_assume.json
  tags               = var.tags
}

data "aws_iam_policy_document" "task_telemetry" {
  # awsemf writes to a log group that Terraform created, so it never needs CreateLogGroup,
  # PutRetentionPolicy or DescribeLogStreams. The log group is KMS encrypted, and writers need no
  # KMS permission: CloudWatch Logs uses the key under the key policy.
  statement {
    sid       = "WriteMetricEvents"
    effect    = "Allow"
    actions   = ["logs:CreateLogStream", "logs:PutLogEvents"]
    resources = ["${aws_cloudwatch_log_group.metrics.arn}:log-stream:*"]
  }

  # X-Ray has no resource-level permissions for PutTraceSegments, so the resource is "*".
  # The condition limits it to this region. The sampling-rule actions are not needed:
  # the SDK samples on its own ratio and the collector has no remote sampling.
  statement {
    sid       = "SendTraceSegments"
    effect    = "Allow"
    actions   = ["xray:PutTraceSegments"]
    resources = ["*"]

    condition {
      test     = "StringEquals"
      variable = "aws:RequestedRegion"
      values   = [data.aws_region.current.region]
    }
  }
}

resource "aws_iam_role_policy" "task_telemetry" {
  name   = "${var.name}-task-telemetry"
  role   = aws_iam_role.task.id
  policy = data.aws_iam_policy_document.task_telemetry.json
}
```

- The comment states the design: the application itself calls no AWS API. The role exists for the collector sidecar, and ECS gives one task role to every container in the task, so the server could use these actions too. They only write telemetry; nothing in them reads data.
- `resource "aws_iam_role" "task"`: `name`, the shared trust policy and standard tags, unchanged from Task 1.
- `WriteMetricEvents`: `logs:CreateLogStream` and `logs:PutLogEvents` on log streams of the metrics log group only. The EMF exporter needs `CreateLogGroup` and `PutRetentionPolicy` only when the group is missing, and Terraform creates it, so they are not granted. The list comes from the exporter's source; it is not tested against an account.
- `SendTraceSegments`: `xray:PutTraceSegments` has no resource-level scoping, so the resource is `*`, and `aws:RequestedRegion` limits it to this region. `PutTelemetryRecords` and the sampling-rule actions are not granted: the exporter's telemetry is off by default and the SDK samples by ratio.
- `resource "aws_iam_role_policy" "task_telemetry"`: an inline policy, so it is created and destroyed with the role.

#### security_groups.tf

**ALB security group — lookup, group and rules**

```hcl modules/service/security_groups.tf
# CloudFront origin-facing addresses. AWS lists this prefix list as a valid way to admit VPC origin traffic.
data "aws_ec2_managed_prefix_list" "cloudfront" {
  name = "com.amazonaws.global.cloudfront.origin-facing"
}

resource "aws_security_group" "alb" {
  name        = "${var.name}-alb"
  description = "Internal ALB: HTTPS from CloudFront VPC origin only"
  vpc_id      = var.vpc_id
  tags        = merge(var.tags, { Name = "${var.name}-alb" })

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_vpc_security_group_ingress_rule" "alb_https_from_cloudfront" {
  security_group_id = aws_security_group.alb.id
  description       = "HTTPS from CloudFront origin-facing prefix list"
  prefix_list_id    = data.aws_ec2_managed_prefix_list.cloudfront.id
  ip_protocol       = "tcp"
  from_port         = 443
  to_port           = 443
}

resource "aws_vpc_security_group_egress_rule" "alb_to_tasks" {
  security_group_id            = aws_security_group.alb.id
  description                  = "Forward to tasks"
  referenced_security_group_id = aws_security_group.task.id
  ip_protocol                  = "tcp"
  from_port                    = var.container_port
  to_port                      = var.container_port
}
```

- `data "aws_ec2_managed_prefix_list" "cloudfront"`: looks up the AWS-managed prefix list `com.amazonaws.global.cloudfront.origin-facing`. It holds the CloudFront addresses that contact origins, and AWS keeps it current, so no IP ranges are hardcoded.
- `resource "aws_security_group" "alb"`: the firewall on the load balancer.
  - `name` and `description`: the description states the intent, HTTPS from the CloudFront VPC origin only.
  - `vpc_id = var.vpc_id`: the VPC from the network module.
  - `tags = merge(var.tags, { Name = "${var.name}-alb" })`: standard tags plus a `Name` tag, which the console shows as the resource name.
  - `lifecycle { create_before_destroy = true }`: when a change forces replacement, the new group exists before the old is deleted. A group still attached to a network interface cannot be deleted, so the default destroy-first order would fail or cause an outage.
- `resource "aws_vpc_security_group_ingress_rule" "alb_https_from_cloudfront"`: one standalone rule per resource, which avoids the conflicts of inline rules.
  - `security_group_id = aws_security_group.alb.id`: the group it belongs to.
  - `prefix_list_id = data.aws_ec2_managed_prefix_list.cloudfront.id`: the source is the CloudFront list, so nothing else can reach the ALB.
  - `ip_protocol = "tcp"`, `from_port = 443`, `to_port = 443`: HTTPS only.
- `resource "aws_vpc_security_group_egress_rule" "alb_to_tasks"`: the ALB may send traffic only to the tasks.
  - `referenced_security_group_id = aws_security_group.task.id`: destination is the task group, not a CIDR range.
  - `ip_protocol = "tcp"`, `from_port` and `to_port = var.container_port`: only the application port.

**Task security group — group and rules**

```hcl modules/service/security_groups.tf
resource "aws_security_group" "task" {
  name        = "${var.name}-task"
  description = "Fargate tasks: traffic from the ALB in, HTTPS and database out"
  vpc_id      = var.vpc_id
  tags        = merge(var.tags, { Name = "${var.name}-task" })

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_vpc_security_group_ingress_rule" "task_from_alb" {
  security_group_id            = aws_security_group.task.id
  description                  = "Application traffic from the ALB"
  referenced_security_group_id = aws_security_group.alb.id
  ip_protocol                  = "tcp"
  from_port                    = var.container_port
  to_port                      = var.container_port
}

# OpenAI publishes no stable address list, so egress to the internet is open on 443.
# NAT gateways and VPC endpoints carry it; ECR, Secrets Manager and Logs use the same port.
resource "aws_vpc_security_group_egress_rule" "task_https" {
  security_group_id = aws_security_group.task.id
  description       = "HTTPS to OpenAI, ECR, Secrets Manager and CloudWatch Logs"
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "tcp"
  from_port         = 443
  to_port           = 443
}

resource "aws_vpc_security_group_egress_rule" "task_to_db" {
  security_group_id            = aws_security_group.task.id
  description                  = "Database"
  referenced_security_group_id = var.db_security_group_id
  ip_protocol                  = "tcp"
  from_port                    = var.db_port
  to_port                      = var.db_port
}

# This module owns the rule that lets tasks reach the database.
resource "aws_vpc_security_group_ingress_rule" "db_from_task" {
  security_group_id            = var.db_security_group_id
  description                  = "Database access from ${var.name} tasks"
  referenced_security_group_id = aws_security_group.task.id
  ip_protocol                  = "tcp"
  from_port                    = var.db_port
  to_port                      = var.db_port
}
```

- `resource "aws_security_group" "task"`: the firewall on the Fargate tasks. The description summarises the policy: traffic from the ALB in, HTTPS and database out.
  - `vpc_id`, `tags` with a `Name` tag, and `create_before_destroy`: as for the ALB group.
- `resource "aws_vpc_security_group_ingress_rule" "task_from_alb"`: the only inbound path to a task.
  - `referenced_security_group_id = aws_security_group.alb.id`: only members of the ALB group, not a subnet range.
  - `ip_protocol = "tcp"`, `from_port` and `to_port = var.container_port`: the application port. Together with `alb_to_tasks` this opens the hop in both directions.
- `resource "aws_vpc_security_group_egress_rule" "task_https"`: outbound HTTPS.
  - The comment gives the reason: OpenAI publishes no stable address list, so a narrower rule is not possible. Traffic leaves through NAT gateways and VPC endpoints.
  - `cidr_ipv4 = "0.0.0.0/0"`, `ip_protocol = "tcp"`, `from_port` and `to_port = 443`: any destination on 443. The same rule covers ECR image pulls, Secrets Manager and CloudWatch Logs, which also use 443.
- `resource "aws_vpc_security_group_egress_rule" "task_to_db"`: outbound database traffic.
  - `referenced_security_group_id = var.db_security_group_id`: only the database group passed in from the data module.
  - `from_port` and `to_port = var.db_port`: the database port.
- `resource "aws_vpc_security_group_ingress_rule" "db_from_task"`: the matching inbound rule, created on the database's group.
  - The comment states ownership: this module owns the rule that lets tasks reach the database, so the data module does not need to know about the service.
  - `security_group_id = var.db_security_group_id`: the rule is attached to the database group, not a group from this module.
  - `description = "Database access from ${var.name} tasks"`: names the source so the rule is identifiable in the database group.
  - `referenced_security_group_id = aws_security_group.task.id`: only the task group may connect.

#### acm.tf

**ALB certificate — `aws_acm_certificate.alb`, validation records and validation**

```hcl modules/service/acm.tf
resource "aws_acm_certificate" "alb" {
  domain_name       = var.domain_name
  validation_method = "DNS"
  tags              = merge(var.tags, { Name = "${var.name}-alb" })

  # A listener may still use the old certificate while a new one validates.
  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_route53_record" "alb_cert_validation" {
  for_each = {
    for o in aws_acm_certificate.alb.domain_validation_options : o.domain_name => {
      name   = o.resource_record_name
      type   = o.resource_record_type
      record = o.resource_record_value
    }
  }

  zone_id = var.route53_zone_id
  name    = each.value.name
  type    = each.value.type
  records = [each.value.record]
  ttl     = 60
  # The edge module validates the same name in us-east-1 and produces the identical record.
  allow_overwrite = true
}

resource "aws_acm_certificate_validation" "alb" {
  certificate_arn         = aws_acm_certificate.alb.arn
  validation_record_fqdns = [for r in aws_route53_record.alb_cert_validation : r.fqdn]
}
```

- `resource "aws_acm_certificate" "alb"`: the certificate the HTTPS listener presents. The ALB terminates TLS from CloudFront, which connects to it by the public domain name.
  - `domain_name = var.domain_name`: the hostname the certificate covers.
  - `validation_method = "DNS"`: proof of ownership through a DNS record, which Terraform can create and which renews automatically while the record exists.
  - `tags = merge(var.tags, { Name = "${var.name}-alb" })`: standard tags plus a `Name` tag.
  - `lifecycle { create_before_destroy = true }`: a listener may still use the old certificate while a new one validates, so the replacement must exist first.
- `resource "aws_route53_record" "alb_cert_validation"`: creates the validation CNAME.
  - `for_each = { for o in ...domain_validation_options : o.domain_name => {...} }`: ACM reports the required record only after the certificate exists, and may report several. The `for` expression turns the options into a map keyed by domain, so each gets one record. The three fields `name`, `type` and `record` come from `resource_record_name`, `resource_record_type` and `resource_record_value`.
  - `zone_id = var.route53_zone_id`: the hosted zone that owns the domain.
  - `name`, `type`, `records = [each.value.record]`: the values ACM asked for.
  - `ttl = 60`: a short TTL so a correction propagates quickly.
  - `allow_overwrite = true`: the comment explains it. The edge module validates the same name in us-east-1 and produces the identical record. Without this, whichever module applies second fails on a record that already exists.
- `resource "aws_acm_certificate_validation" "alb"`: a waiting resource with no AWS object behind it.
  - `certificate_arn = aws_acm_certificate.alb.arn`: the certificate to wait for.
  - `validation_record_fqdns = [for r in aws_route53_record.alb_cert_validation : r.fqdn]`: depends on the records, so Terraform blocks until ACM reports the certificate issued. The listener references this resource's `certificate_arn`, so it cannot be created before the certificate is usable.

#### alb.tf

**Load balancer — `aws_lb.this`**

```hcl modules/service/alb.tf
# ALB access logs are not enabled: ALB log delivery cannot write to a bucket encrypted with a customer-managed key.
resource "aws_lb" "this" {
  name               = "${var.name}-alb"
  load_balancer_type = "application"
  # Internal: reachable only from CloudFront through a VPC origin.
  internal        = true
  subnets         = var.private_subnet_ids
  security_groups = [aws_security_group.alb.id]
  idle_timeout    = local.alb_idle_timeout_seconds
  # Reject malformed headers instead of passing them to the application.
  drop_invalid_header_fields = true
  tags                       = var.tags
}
```

- The leading comment records a decision: access logs are off, because ALB log delivery cannot write to a bucket encrypted with a customer-managed key.
- `name = "${var.name}-alb"`: prefixed name.
- `load_balancer_type = "application"`: layer 7, needed for HTTP routing and WebSocket upgrades.
- `internal = true`: no public addresses. The load balancer is reachable only from inside the VPC, and the edge module's CloudFront VPC origin is the single way in.
- `subnets = var.private_subnet_ids`: placed in the private subnets, one per availability zone.
- `security_groups = [aws_security_group.alb.id]`: the ALB group, which admits only the CloudFront prefix list.
- `idle_timeout = local.alb_idle_timeout_seconds`: 600 seconds, explained in the locals.
- `drop_invalid_header_fields = true`: rejects requests with malformed headers instead of passing them to the application, so the application only sees well-formed requests.
- `tags = var.tags`: standard tags.

**Target group — `aws_lb_target_group.server`**

```hcl modules/service/alb.tf
resource "aws_lb_target_group" "server" {
  name        = "${var.name}-server"
  port        = var.container_port
  protocol    = "HTTP"
  vpc_id      = var.vpc_id
  target_type = "ip"
  # Fast drain: WebSocket clients reconnect, and the container stops within stopTimeout anyway.
  deregistration_delay = local.alb_deregistration_delay_seconds
  # Long-lived WebSockets make round robin uneven; route new connections to the least busy task.
  load_balancing_algorithm_type = "least_outstanding_requests"

  health_check {
    path                = var.health_check_path
    protocol            = "HTTP"
    matcher             = "200"
    interval            = 15
    timeout             = 5
    healthy_threshold   = 2
    unhealthy_threshold = 3
  }

  tags = var.tags
}
```

- `name = "${var.name}-server"`: prefixed name.
- `port = var.container_port` and `protocol = "HTTP"`: the ALB talks plain HTTP to tasks. TLS ends at the ALB, and the task group admits only the ALB.
- `vpc_id = var.vpc_id`: the VPC the targets live in.
- `target_type = "ip"`: Fargate tasks in `awsvpc` mode have their own network interface, so they register by IP. `instance` targets do not work for them.
- `deregistration_delay = local.alb_deregistration_delay_seconds`: a fast drain of 60 seconds. WebSocket clients reconnect, and the container stops within `stopTimeout` anyway, so the default 300 would only slow deploys.
- `load_balancing_algorithm_type = "least_outstanding_requests"`: long-lived WebSockets make round robin uneven, so new connections go to the least busy task.
- `health_check`: decides whether a task receives traffic.
  - `path = var.health_check_path` and `protocol = "HTTP"`: the application's health endpoint.
  - `matcher = "200"`: only a 200 counts as healthy.
  - `interval = 15` and `timeout = 5`: probe every 15 seconds and wait up to 5 for an answer.
  - `healthy_threshold = 2`: two consecutive successes to join, about 30 seconds.
  - `unhealthy_threshold = 3`: three consecutive failures to leave, about 45 seconds. Slightly more tolerant than the entry threshold, so a single slow probe does not remove a task.
- `tags = var.tags`: standard tags.

**HTTPS listener — `aws_lb_listener.https`**

```hcl modules/service/alb.tf
resource "aws_lb_listener" "https" {
  load_balancer_arn = aws_lb.this.arn
  port              = 443
  protocol          = "HTTPS"
  # TLS 1.2 and 1.3 only, ECDHE with AES-GCM; this is the policy AWS recommends.
  ssl_policy      = "ELBSecurityPolicy-TLS13-1-2-Res-PQ-2025-09"
  certificate_arn = aws_acm_certificate_validation.alb.certificate_arn

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

  tags = var.tags
}
```

- `load_balancer_arn = aws_lb.this.arn`: the listener belongs to this load balancer.
- `port = 443` and `protocol = "HTTPS"`: the only listener. There is no port 80, matching the security group, which admits only 443.
- `ssl_policy = "ELBSecurityPolicy-TLS13-1-2-Res-PQ-2025-09"`: TLS 1.2 and 1.3 only, ECDHE with AES-GCM, per the comment the policy AWS recommends.
- `certificate_arn = aws_acm_certificate_validation.alb.certificate_arn`: read from the validation resource rather than the certificate, so the listener waits until the certificate is issued.
- `default_action { type = "forward", target_group_arn = ... }`: every request goes to the server target group. The edge module chooses which paths reach the ALB at all, so no listener rules are needed.
- `tags = var.tags`: standard tags.

#### ecs.tf

**Log group — `aws_cloudwatch_log_group.server`**

```hcl modules/service/ecs.tf
resource "aws_cloudwatch_log_group" "server" {
  name              = "/ecs/${var.name}-server"
  retention_in_days = var.log_retention_days
  kms_key_id        = var.logs_kms_key_arn
  tags              = var.tags
}
```

- `name = "/ecs/${var.name}-server"`: the conventional `/ecs/` prefix plus the service name.
- `retention_in_days = var.log_retention_days`: logs expire. Without a value, CloudWatch keeps them forever and the bill grows.
- `kms_key_id = var.logs_kms_key_arn`: encrypts the logs with the customer-managed logs key passed in by the caller. The key policy must allow CloudWatch Logs to use it.
- `tags = var.tags`: standard tags.
- Creating the group in Terraform, rather than letting the log driver create it, is what makes retention and encryption possible.

**Metrics log group — `aws_cloudwatch_log_group.metrics`**

```hcl modules/service/ecs.tf
# Metric events in Embedded Metric Format, written by the collector sidecar. CloudWatch turns each
# event into a metric; the log events are only the transport. They hold counts and the outcome
# label, never document text.
resource "aws_cloudwatch_log_group" "metrics" {
  name              = "/ecs/${var.name}-metrics"
  retention_in_days = var.log_retention_days
  kms_key_id        = var.logs_kms_key_arn
  tags              = var.tags
}
```

- The EMF exporter writes one structured log event per datapoint; CloudWatch extracts the metric `Patent/Server` `suggestions.requests` from it. It needs no `PutMetricData` permission.
- Same retention and KMS key as the server log group. Terraform creates it so the collector never needs `logs:CreateLogGroup`.

**Cluster and capacity providers — `aws_ecs_cluster.this`, `aws_ecs_cluster_capacity_providers.this`**

```hcl modules/service/ecs.tf
resource "aws_ecs_cluster" "this" {
  name = "${var.name}-cluster"

  # Per-task CPU, memory and network metrics.
  setting {
    name  = "containerInsights"
    value = "enabled"
  }

  tags = var.tags
}

resource "aws_ecs_cluster_capacity_providers" "this" {
  cluster_name       = aws_ecs_cluster.this.name
  capacity_providers = ["FARGATE", "FARGATE_SPOT"]
}
```

- `resource "aws_ecs_cluster" "this"`: the logical grouping the service runs in. Fargate has no instances to manage.
  - `name = "${var.name}-cluster"`: prefixed name.
  - `setting { name = "containerInsights", value = "enabled" }`: per-task CPU, memory and network metrics in CloudWatch, at extra cost.
  - `tags = var.tags`: standard tags.
- `resource "aws_ecs_cluster_capacity_providers" "this"`: registers capacity providers with the cluster.
  - `cluster_name = aws_ecs_cluster.this.name`: the target cluster.
  - `capacity_providers = ["FARGATE", "FARGATE_SPOT"]`: both are registered so the service's `use_fargate_spot` switch is a plan-time change only. A service can only use a provider already associated with its cluster.

**Task definition — `aws_ecs_task_definition.server`**

```hcl modules/service/ecs.tf
resource "aws_ecs_task_definition" "server" {
  family                   = "${var.name}-server"
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  cpu                      = tostring(var.cpu)
  memory                   = tostring(var.memory)
  execution_role_arn       = aws_iam_role.task_execution.arn
  task_role_arn            = aws_iam_role.task.arn

  # Assumed architecture: images are built for linux/amd64.
  runtime_platform {
    operating_system_family = "LINUX"
    cpu_architecture        = "X86_64"
  }

  # Writable scratch space, because the root file system is read-only and Python/uvicorn write to /tmp.
  volume {
    name = "tmp"
  }

  container_definitions = jsonencode([
    {
      name      = local.container_name
      image     = "${aws_ecr_repository.server.repository_url}:${var.image_tag}"
      essential = true
      # The rest of the task after the collector. Without a value Fargate gives the server the
      # smallest CPU share, and the collector would win every contention.
      cpu    = var.cpu - local.otel_collector_cpu
      memory = var.memory - local.otel_collector_memory_mib

      # The collector must outlive the server. Containers stop in reverse dependency order, so the
      # server drains its open WebSockets (up to stopTimeout) while it can still export. START only
      # waits until the collector container has started, not until it is healthy, so a collector
      # that crashes or never gets ready cannot hold the server back.
      dependsOn = [
        { containerName = "otel-collector", condition = "START" }
      ]

      portMappings = [
        {
          containerPort = var.container_port
          protocol      = "tcp"
        }
      ]

      readonlyRootFilesystem = true
      # Reap child processes and forward signals so shutdown is clean.
      linuxParameters = { initProcessEnabled = true }
      # Time for open WebSockets and in-flight OpenAI streams to finish after SIGTERM (Fargate maximum is 120).
      stopTimeout = local.ecs_task_stop_timeout_seconds

      mountPoints = [
        {
          sourceVolume  = "tmp"
          containerPath = "/tmp"
          readOnly      = false
        }
      ]

      environment = [
        { name = "OPENAI_MODEL", value = var.openai_model },
        { name = "DB_HOST", value = var.db_host },
        { name = "DB_PORT", value = tostring(var.db_port) },
        { name = "DB_NAME", value = var.db_name },
        # Telemetry goes to the collector sidecar over OTLP/HTTP; the application does not know the back end.
        # The release SHA is not set here: the image carries it (RELEASE_SHA), so a deploy that only
        # swaps the image still reports the right version.
        { name = "OTEL_EXPORTER_OTLP_ENDPOINT", value = "http://localhost:4318" },
        { name = "OTEL_SERVICE_NAME", value = "patent-server" },
        { name = "OTEL_RESOURCE_ATTRIBUTES", value = "deployment.environment.name=${var.environment}" },
        { name = "OTEL_TRACES_SAMPLER", value = "parentbased_traceidratio" },
        { name = "OTEL_TRACES_SAMPLER_ARG", value = tostring(var.trace_sample_ratio) },
      ]

      # valueFrom with a JSON key: <secret-arn>:<json-key>:<version-stage>:<version-id>.
      secrets = [
        { name = "OPENAI_API_KEY", valueFrom = var.openai_secret_arn },
        { name = "DB_USER", valueFrom = "${var.db_master_secret_arn}:username::" },
        { name = "DB_PASSWORD", valueFrom = "${var.db_master_secret_arn}:password::" },
      ]

      logConfiguration = {
        logDriver = "awslogs"
        options = {
          "awslogs-group"         = aws_cloudwatch_log_group.server.name
          "awslogs-region"        = data.aws_region.current.region
          "awslogs-stream-prefix" = "server"
        }
      }
    },
    {
      name  = "otel-collector"
      image = local.otel_collector_image
      # A collector failure must not stop the task: the server serves requests without telemetry.
      # ECS does not restart a non-essential container, so a crashed collector stays down until the
      # task is replaced. Its container health status shows in the console. The task then sends no
      # metrics, and the alarm treats a missing metric as not breaching.
      essential = false

      user                   = local.otel_collector_user
      readonlyRootFilesystem = true
      cpu                    = local.otel_collector_cpu
      memory                 = local.otel_collector_memory_mib

      environment = [
        # The whole collector config; the file is observability/collector/aws.yaml.
        { name = "AOT_CONFIG_CONTENT", value = local.otel_collector_config },
        { name = "EMF_LOG_GROUP_NAME", value = aws_cloudwatch_log_group.metrics.name },
        # Explicit, so the exporters do not depend on the metadata lookup to find the region.
        { name = "AWS_REGION", value = data.aws_region.current.region },
      ]

      # /healthcheck is part of the image; it calls the health_check extension in aws.yaml.
      healthCheck = {
        command     = ["CMD", "/healthcheck"]
        interval    = 30
        timeout     = 5
        retries     = 3
        startPeriod = 10
      }

      logConfiguration = {
        logDriver = "awslogs"
        options = {
          "awslogs-group"         = aws_cloudwatch_log_group.server.name
          "awslogs-region"        = data.aws_region.current.region
          "awslogs-stream-prefix" = "otel-collector"
        }
      }
    }
  ])

  tags = var.tags
}
```

- `family = "${var.name}-server"`: the name under which revisions accumulate. The deploy pipeline registers new revisions into this family.
- `requires_compatibilities = ["FARGATE"]`: validates the definition against Fargate rules.
- `network_mode = "awsvpc"`: required by Fargate. Each task gets its own network interface, which is why the security group and target group use IP targets.
- `cpu = tostring(var.cpu)` and `memory = tostring(var.memory)`: task-level size. The provider takes strings, so numeric variables are converted. Fargate accepts only fixed cpu/memory combinations.
- `execution_role_arn = aws_iam_role.task_execution.arn`: the role ECS uses to pull the image, write logs and fetch secrets.
- `task_role_arn = aws_iam_role.task.arn`: the role the containers run as. It can only write telemetry (see `iam.tf` above).
- `runtime_platform`:
  - `operating_system_family = "LINUX"`: Linux containers.
  - `cpu_architecture = "X86_64"`: the comment flags the assumption that images are built for linux/amd64. An image built for another architecture fails at start-up with an exec format error.
- `volume { name = "tmp" }`: an ephemeral task-scoped volume, writable scratch space. The root file system is read-only and Python and uvicorn write to `/tmp`.
- `container_definitions = jsonencode([...])`: ECS takes the container list as JSON. Two containers follow: `server` and the `otel-collector` sidecar.
  - `name = local.container_name`: must match the service's `load_balancer.container_name`. `register-task-definition.sh` requires exactly one container with this name and copies the sidecar unchanged.
  - `image = "${aws_ecr_repository.server.repository_url}:${var.image_tag}"`: the repository from `ecr.tf` and a tag from a variable. Tags are immutable, so the value identifies one build.
  - `essential = true`: if this container stops, the whole task stops and ECS replaces it.
  - `cpu` and `memory`: the task size minus the sidecar's share. With no `cpu`, Fargate would give the server the smallest CPU share. `memory` is a hard limit, 768 MiB at the default task size.
  - `dependsOn` with `condition = "START"`: the server starts after the collector container has started, not after it is healthy, so a collector that never gets ready cannot hold the server back. Containers stop in reverse order, so the collector outlives the server's drain and the last metrics get out. A failed pull of the collector image could still keep the task from starting.
  - `portMappings`: `containerPort = var.container_port` and `protocol = "tcp"` declare the port the application listens on. With `awsvpc` there is no host port mapping, and the ALB reaches the container directly.
  - `readonlyRootFilesystem = true`: the container cannot write to its own file system, so an attacker who gets code execution cannot modify binaries or drop files. The `/tmp` mount is the only writable path.
  - `linuxParameters = { initProcessEnabled = true }`: runs a small init as PID 1 that reaps child processes and forwards signals, so shutdown is clean.
  - `stopTimeout = local.ecs_task_stop_timeout_seconds`: time between SIGTERM and SIGKILL. Open WebSockets and in-flight OpenAI streams need time to finish. The comment gives 120 as the Fargate maximum.
  - `mountPoints`: attaches the `tmp` volume.
    - `sourceVolume = "tmp"`: the volume declared above.
    - `containerPath = "/tmp"`: where it appears in the container.
    - `readOnly = false`: this is the point of the mount.
  - `environment`: plain, non-secret configuration.
    - `OPENAI_MODEL` from `var.openai_model`: which model the application calls.
    - `DB_HOST`, `DB_PORT` and `DB_NAME`: the database address. `tostring(var.db_port)` is needed because environment values are strings.
    - `OTEL_EXPORTER_OTLP_ENDPOINT = "http://localhost:4318"`: the sidecar. Containers of one `awsvpc` task share a network namespace, so `localhost` reaches it.
    - `OTEL_SERVICE_NAME`, `OTEL_RESOURCE_ATTRIBUTES` (`deployment.environment.name` from `var.environment`) and the sampler from `var.trace_sample_ratio`: standard OpenTelemetry variables. The release SHA is not here: the image carries it, because a release changes only the image.
  - `secrets`: ECS reads these at start-up using the execution role and injects them as environment variables. The values never appear in the task definition or in Terraform state. The comment gives the `valueFrom` format for a JSON key, `<secret-arn>:<json-key>:<version-stage>:<version-id>`.
    - `OPENAI_API_KEY` with `valueFrom = var.openai_secret_arn`: the whole secret value.
    - `DB_USER` with `"${var.db_master_secret_arn}:username::"`: the `username` key of the database's JSON secret. The two trailing colons leave version stage and version ID empty, which selects the current version.
    - `DB_PASSWORD` with `"${var.db_master_secret_arn}:password::"`: the `password` key of the same secret.
  - `logConfiguration`: sends stdout and stderr to CloudWatch.
    - `logDriver = "awslogs"`: the built-in driver.
    - `awslogs-group = aws_cloudwatch_log_group.server.name`: the group defined above.
    - `awslogs-region = data.aws_region.current.region`: the current region.
    - `awslogs-stream-prefix = "server"`: streams are named `server/<container>/<task-id>`.
- The `otel-collector` container (AWS Distro for OpenTelemetry):
  - `essential = false`: a collector failure must not stop the task. ECS does not restart it, so a dead collector means no metrics or traces from that task until it is replaced, and the alarm treats the missing metric as not breaching.
  - `user`, `readonlyRootFilesystem = true`, `cpu`, `memory`: non-root, immutable, and a fixed share of the task.
  - `AOT_CONFIG_CONTENT`: ADOT reads its whole config from this variable, here the contents of `observability/collector/aws.yaml`. A change reaches running tasks at the next release, like every task definition setting.
  - `EMF_LOG_GROUP_NAME` and `AWS_REGION`: the values `aws.yaml` reads with `${env:...}`, so one file serves every environment.
  - `healthCheck`: `/healthcheck` is in the image and calls the collector's `health_check` extension. The status shows in the console; nothing alarms on it.
  - `logConfiguration`: the server's log group with stream prefix `otel-collector`.
- `tags = var.tags`: standard tags.

**Service — `aws_ecs_service.server`**

```hcl modules/service/ecs.tf
resource "aws_ecs_service" "server" {
  name            = "${var.name}-server"
  cluster         = aws_ecs_cluster.this.id
  task_definition = aws_ecs_task_definition.server.arn
  desired_count   = var.min_tasks

  # Capacity provider strategy replaces launch_type; the two conflict.
  capacity_provider_strategy {
    capacity_provider = var.use_fargate_spot ? "FARGATE_SPOT" : "FARGATE"
    weight            = 1
  }

  # Never drop below the desired count; surge to double for a rolling deploy.
  deployment_minimum_healthy_percent = 100
  deployment_maximum_percent         = 200

  # Stop a deploy whose tasks never become healthy and return to the last good revision.
  deployment_circuit_breaker {
    enable   = true
    rollback = true
  }

  # Also roll back when the 5xx alarm or the suggestion failure alarm fires during a deploy.
  alarms {
    alarm_names = local.rollback_alarm_names
    enable      = true
    rollback    = true
  }

  # Ignore target-group failures while a new task starts.
  health_check_grace_period_seconds = local.health_check_grace_period_seconds
  availability_zone_rebalancing     = "ENABLED"
  enable_execute_command            = false
  enable_ecs_managed_tags           = true
  propagate_tags                    = "SERVICE"
  # The bootstrap image tag does not exist until the first push, so a steady-state wait would hang the first apply.
  wait_for_steady_state = false

  network_configuration {
    subnets          = var.private_subnet_ids
    security_groups  = [aws_security_group.task.id]
    assign_public_ip = false
  }

  load_balancer {
    target_group_arn = aws_lb_target_group.server.arn
    container_name   = local.container_name
    container_port   = var.container_port
  }

  # The deploy pipeline owns the task definition revision; autoscaling owns the count.
  lifecycle {
    ignore_changes = [task_definition, desired_count]
  }

  depends_on = [
    aws_lb_listener.https,
    aws_ecs_cluster_capacity_providers.this,
    aws_iam_role_policy.task_execution_secrets,
    aws_iam_role_policy_attachment.task_execution_managed,
  ]

  tags = var.tags
}
```

- `name = "${var.name}-server"`: prefixed name.
- `cluster = aws_ecs_cluster.this.id` and `task_definition = aws_ecs_task_definition.server.arn`: where the service runs and what it runs initially.
- `desired_count = var.min_tasks`: the starting task count, which is also the autoscaling floor.
- `capacity_provider_strategy`: the comment notes it replaces `launch_type`, and the two conflict.
  - `capacity_provider = var.use_fargate_spot ? "FARGATE_SPOT" : "FARGATE"`: on-demand by default. Spot is cheaper but its tasks can be interrupted.
  - `weight = 1`: all tasks use the one provider.
- `deployment_minimum_healthy_percent = 100` and `deployment_maximum_percent = 200`: a rolling deploy starts new tasks up to double the count and never takes capacity below the desired count, so a deploy causes no loss of capacity.
- `deployment_circuit_breaker { enable = true, rollback = true }`: if new tasks repeatedly fail to become healthy, ECS stops the deploy and returns to the last good revision.
- `alarms`: a second rollback trigger.
  - `alarm_names = local.rollback_alarm_names`: the 5xx-ratio alarm and the suggestion failure-ratio alarm, defined in `alarms.tf`.
  - `enable = true` and `rollback = true`: ECS watches the alarms during a deploy and rolls back if one fires. The 5xx alarm catches a build that starts but serves errors, which the circuit breaker does not. The suggestion alarm catches a build whose AI suggestions fail with no 5xx at all.
- `health_check_grace_period_seconds = local.health_check_grace_period_seconds`: ignore ALB health results for a new task for 60 seconds.
- `availability_zone_rebalancing = "ENABLED"`: ECS moves tasks to keep them evenly spread across zones.
- `enable_execute_command = false`: no `ECS Exec` shell into tasks, which would need extra task role permissions.
- `enable_ecs_managed_tags = true` and `propagate_tags = "SERVICE"`: tasks carry ECS metadata tags and the service's tags, so task cost and ownership are attributable.
- `wait_for_steady_state = false`: the comment explains it. The bootstrap image tag does not exist until the first push, so waiting would hang the first apply.
- `network_configuration`:
  - `subnets = var.private_subnet_ids`: tasks run in private subnets.
  - `security_groups = [aws_security_group.task.id]`: the task group.
  - `assign_public_ip = false`: no public address. Outbound traffic goes through NAT or endpoints.
- `load_balancer`: registers tasks with the target group.
  - `target_group_arn = aws_lb_target_group.server.arn`: the group from `alb.tf`.
  - `container_name = local.container_name` and `container_port = var.container_port`: which container and port receive traffic. The name must match the task definition.
- `lifecycle { ignore_changes = [task_definition, desired_count] }`: the deploy pipeline owns the task definition revision and autoscaling owns the count. Without it, every `terraform apply` would revert both.
- `depends_on`: ordering that no attribute reference expresses.
  - `aws_lb_listener.https`: ECS rejects a service whose target group is not yet attached to a listener.
  - `aws_ecs_cluster_capacity_providers.this`: the provider must be associated before the service uses it.
  - `aws_iam_role_policy.task_execution_secrets` and `aws_iam_role_policy_attachment.task_execution_managed`: the execution role needs its permissions before the first task starts, or the first tasks fail to pull the image or read secrets.
- `tags = var.tags`: standard tags.

#### autoscaling.tf

**Scaling target — `aws_appautoscaling_target.server`**

```hcl modules/service/autoscaling.tf
resource "aws_appautoscaling_target" "server" {
  service_namespace  = "ecs"
  scalable_dimension = "ecs:service:DesiredCount"
  resource_id        = "service/${aws_ecs_cluster.this.name}/${aws_ecs_service.server.name}"
  min_capacity       = var.min_tasks
  max_capacity       = var.max_tasks
  tags               = var.tags
}
```

- `service_namespace = "ecs"` and `scalable_dimension = "ecs:service:DesiredCount"`: Application Auto Scaling manages the service's desired task count.
- `resource_id = "service/${aws_ecs_cluster.this.name}/${aws_ecs_service.server.name}"`: the identifier format Application Auto Scaling requires for an ECS service.
- `min_capacity = var.min_tasks` and `max_capacity = var.max_tasks`: the bounds the policies stay within. The validation on `max_tasks` ensures the range is not empty.
- `tags = var.tags`: standard tags.

**CPU policy — `aws_appautoscaling_policy.cpu`**

```hcl modules/service/autoscaling.tf
resource "aws_appautoscaling_policy" "cpu" {
  name               = "${var.name}-server-cpu"
  policy_type        = "TargetTrackingScaling"
  service_namespace  = aws_appautoscaling_target.server.service_namespace
  scalable_dimension = aws_appautoscaling_target.server.scalable_dimension
  resource_id        = aws_appautoscaling_target.server.resource_id

  target_tracking_scaling_policy_configuration {
    target_value       = local.autoscaling_cpu_target_percent
    scale_out_cooldown = local.autoscaling_scale_out_cooldown_seconds
    scale_in_cooldown  = local.autoscaling_scale_in_cooldown_seconds

    predefined_metric_specification {
      predefined_metric_type = "ECSServiceAverageCPUUtilization"
    }
  }
}
```

- `name = "${var.name}-server-cpu"`: prefixed name.
- `policy_type = "TargetTrackingScaling"`: the service adds or removes tasks to hold a metric near a target, with no step thresholds to maintain.
- `service_namespace`, `scalable_dimension` and `resource_id`: copied from the target, which binds the policy to it and orders creation.
- `target_tracking_scaling_policy_configuration`:
  - `target_value = local.autoscaling_cpu_target_percent`: hold average CPU near 60 percent.
  - `scale_out_cooldown = local.autoscaling_scale_out_cooldown_seconds`: wait 60 seconds after a scale-out before another.
  - `scale_in_cooldown = local.autoscaling_scale_in_cooldown_seconds`: wait 300 seconds after a scale-in. Slow scale-in avoids oscillation.
  - `predefined_metric_specification { predefined_metric_type = "ECSServiceAverageCPUUtilization" }`: AWS's built-in service-wide CPU metric, so no custom metric is needed.

**Request-count policy — `aws_appautoscaling_policy.requests`**

```hcl modules/service/autoscaling.tf
# ALBRequestCountPerTarget counts new HTTP requests and WebSocket upgrades, not open WebSocket connections.
resource "aws_appautoscaling_policy" "requests" {
  name               = "${var.name}-server-requests"
  policy_type        = "TargetTrackingScaling"
  service_namespace  = aws_appautoscaling_target.server.service_namespace
  scalable_dimension = aws_appautoscaling_target.server.scalable_dimension
  resource_id        = aws_appautoscaling_target.server.resource_id

  target_tracking_scaling_policy_configuration {
    target_value       = local.autoscaling_requests_per_target
    scale_out_cooldown = local.autoscaling_scale_out_cooldown_seconds
    scale_in_cooldown  = local.autoscaling_scale_in_cooldown_seconds

    predefined_metric_specification {
      predefined_metric_type = "ALBRequestCountPerTarget"
      resource_label         = "${aws_lb.this.arn_suffix}/${aws_lb_target_group.server.arn_suffix}"
    }
  }
}
```

- The comment explains the limit: `ALBRequestCountPerTarget` counts new HTTP requests and WebSocket upgrades, not open WebSocket connections. It scales on arrival rate, not on how many sessions are held open, so CPU stays the policy that reacts to long sessions.
- `name`, `policy_type`, `service_namespace`, `scalable_dimension`, `resource_id`: as for the CPU policy.
- `target_value = local.autoscaling_requests_per_target`: hold about 500 requests per target.
- `scale_out_cooldown` and `scale_in_cooldown`: the same shared cooldowns.
- `predefined_metric_specification`:
  - `predefined_metric_type = "ALBRequestCountPerTarget"`: requests the ALB sends to each task.
  - `resource_label = "${aws_lb.this.arn_suffix}/${aws_lb_target_group.server.arn_suffix}"`: identifies which load balancer and target group to measure. Both suffixes are required in this form.
- With two policies, the service scales out when either wants more tasks and scales in only when both agree.

#### alarms.tf

**Alarm settings — `local.alarm_*`**

```hcl modules/service/alarms.tf
locals {
  # Starting values for every alarm; tune them from production traffic.
  alarm_period_seconds           = 60
  alarm_evaluation_periods       = 3
  alarm_5xx_ratio_percent        = 5
  alarm_5xx_min_requests         = 20
  alarm_p95_response_time_second = 2

  alarm_dimensions = {
    LoadBalancer = aws_lb.this.arn_suffix
    TargetGroup  = aws_lb_target_group.server.arn_suffix
  }

  # Failure ratio of AI suggestion requests. Objective: 99.5% of requests succeed (a starting value),
  # so the error budget is 0.5%. A burn rate of 14.4 spends 2% of a 30-day budget in one hour.
  # The threshold is a percent here (7.2) and a fraction (14.4 * 0.005) in the Prometheus rule.
  alarm_suggestion_error_budget_percent = 0.5
  alarm_suggestion_burn_rate            = 14.4
  alarm_suggestion_failure_percent      = local.alarm_suggestion_burn_rate * local.alarm_suggestion_error_budget_percent
  # CloudWatch evaluates one period per datapoint, so this alarm is the short window of the
  # Prometheus rule: 5 minutes, one period. The 1-hour window exists only in Prometheus.
  alarm_suggestion_period_seconds = 300
  # Below this many requests in a period, one failure is a large percentage by itself.
  alarm_suggestion_min_requests = 10

  # Alarms that ECS watches during a deploy; a release that trips one is rolled back.
  rollback_alarm_names = [
    aws_cloudwatch_metric_alarm.target_5xx_ratio.alarm_name,
    aws_cloudwatch_metric_alarm.suggestion_failure_ratio.alarm_name,
  ]
}
```

- `alarm_period_seconds = 60`: each datapoint is one minute of metrics.
- `alarm_evaluation_periods = 3`: look at the last three periods. Every alarm also sets `datapoints_to_alarm` to the same value, so all three must breach. One bad minute does not fire an alarm.
- `alarm_5xx_ratio_percent = 5`: the 5xx share that fires.
- `alarm_5xx_min_requests = 20`: below this request count per period the ratio is treated as zero, so one failed request out of two does not read as 50 percent.
- `alarm_p95_response_time_second = 2`: the p95 latency threshold in seconds.
- `alarm_dimensions`: the `LoadBalancer` and `TargetGroup` dimensions, using the ARN suffixes CloudWatch expects. The three ALB alarms share it, so they measure the same targets.
- `alarm_suggestion_*`: the suggestion objective (99.5%, so a 0.5% budget) and the burn rate 14.4 give the threshold, 7.2%, as a computed local rather than a magic number. The period is 5 minutes, the short window of the Prometheus rule. Below 10 requests in a period the ratio counts as zero.
- `rollback_alarm_names`: the two alarms the ECS service watches during a deploy, and the module output of the same name.
- The comment marks all values as starting points to tune from production traffic.

**5xx ratio alarm — `aws_cloudwatch_metric_alarm.target_5xx_ratio`**

```hcl modules/service/alarms.tf
# ECS also watches this alarm during a deploy (rollback_alarm_names); it rolls the deploy back when it fires.
resource "aws_cloudwatch_metric_alarm" "target_5xx_ratio" {
  alarm_name          = "${var.name}-alb-target-5xx-ratio"
  alarm_description   = "Share of ALB requests answered with 5xx by the tasks. Also the ECS deployment rollback alarm."
  comparison_operator = "GreaterThanThreshold"
  threshold           = local.alarm_5xx_ratio_percent
  evaluation_periods  = local.alarm_evaluation_periods
  datapoints_to_alarm = local.alarm_evaluation_periods
  # No traffic is not an outage.
  treat_missing_data = "notBreaching"
  alarm_actions      = [var.alarm_topic_arn]
  ok_actions         = [var.alarm_topic_arn]
  tags               = var.tags

  metric_query {
    id          = "ratio"
    label       = "5xx percent"
    expression  = "IF(requests >= ${local.alarm_5xx_min_requests}, 100 * FILL(errors, 0) / requests, 0)"
    return_data = true
  }

  metric_query {
    id = "errors"
    metric {
      namespace   = "AWS/ApplicationELB"
      metric_name = "HTTPCode_Target_5XX_Count"
      period      = local.alarm_period_seconds
      stat        = "Sum"
      dimensions  = local.alarm_dimensions
    }
  }

  metric_query {
    id = "requests"
    metric {
      namespace   = "AWS/ApplicationELB"
      metric_name = "RequestCount"
      period      = local.alarm_period_seconds
      stat        = "Sum"
      dimensions  = local.alarm_dimensions
    }
  }
}
```

- The comment states the dual role: ECS watches this alarm during a deploy, and it rolls the deploy back when it fires. The service gets it through `local.rollback_alarm_names`.
- `alarm_name` and `alarm_description`: the description repeats the dual role for whoever receives the notification.
- `comparison_operator = "GreaterThanThreshold"` and `threshold = local.alarm_5xx_ratio_percent`: fire when the ratio exceeds 5 percent.
- `evaluation_periods` and `datapoints_to_alarm`: three of three periods must breach.
- `treat_missing_data = "notBreaching"`: no traffic produces no data, and no traffic is not an outage.
- `alarm_actions = [var.alarm_topic_arn]` and `ok_actions = [var.alarm_topic_arn]`: notify the topic from the observability module when the alarm fires and when it recovers.
- `tags = var.tags`: standard tags.
- `metric_query "ratio"`: a metric math query, the one the alarm evaluates.
  - `label = "5xx percent"`: the legend on graphs.
  - `expression = "IF(requests >= 20, 100 * FILL(errors, 0) / requests, 0)"`: the 5xx percentage, but only when at least 20 requests arrived. `FILL(errors, 0)` is needed because the error metric has no datapoint at all in a period with no 5xx responses, and the division would otherwise return nothing.
  - `return_data = true`: this is the series the alarm uses. The other two queries are inputs only.
- `metric_query "errors"`: the numerator, a raw metric.
  - `namespace = "AWS/ApplicationELB"` and `metric_name = "HTTPCode_Target_5XX_Count"`: 5xx responses generated by the tasks. This excludes 5xx the ALB generates itself.
  - `period = local.alarm_period_seconds` and `stat = "Sum"`: total per minute.
  - `dimensions = local.alarm_dimensions`: this load balancer and target group.
- `metric_query "requests"`: the denominator.
  - `metric_name = "RequestCount"`: all requests, with the same period, `Sum` and dimensions.

**Suggestion failure-ratio alarm — `aws_cloudwatch_metric_alarm.suggestion_failure_ratio`**

```hcl modules/service/alarms.tf
# Rolls a release back when the AI suggestion path breaks without any HTTP 5xx: the WebSocket handler
# catches every error, so target_5xx_ratio never sees it. The metric is suggestions.requests, which the
# collector sidecar writes to CloudWatch (observability/collector/aws.yaml).
# Tradeoff: an OpenAI outage during a deploy also trips this alarm and rolls the deploy back.
resource "aws_cloudwatch_metric_alarm" "suggestion_failure_ratio" {
  alarm_name          = "${var.name}-suggestion-failure-ratio"
  alarm_description   = "Share of AI suggestion requests that failed in 5 minutes (model error, timeout or invalid response), above the 14.4x burn rate (7.2%) of a 99.5% objective. Also an ECS deployment rollback alarm."
  comparison_operator = "GreaterThanThreshold"
  threshold           = local.alarm_suggestion_failure_percent
  evaluation_periods  = 1
  datapoints_to_alarm = 1
  # No suggestion requests is not an outage.
  treat_missing_data = "notBreaching"
  alarm_actions      = [var.alarm_topic_arn]
  ok_actions         = [var.alarm_topic_arn]
  tags               = var.tags

  metric_query {
    id          = "ratio"
    label       = "Failed suggestion percent"
    expression  = "IF(requests >= ${local.alarm_suggestion_min_requests}, 100 * failures / requests, 0)"
    return_data = true
  }

  # A series exists only after its first event, so each one is filled with 0 before it is added.
  # bad_request is left out of both sides: a malformed client message is not a service failure.
  metric_query {
    id         = "failures"
    expression = "FILL(ai_error, 0) + FILL(invalid_response, 0)"
  }

  metric_query {
    id         = "requests"
    expression = "FILL(ok, 0) + FILL(ai_error, 0) + FILL(invalid_response, 0)"
  }

  metric_query {
    id = "ok"
    metric {
      namespace   = "Patent/Server"
      metric_name = "suggestions.requests"
      period      = local.alarm_suggestion_period_seconds
      stat        = "Sum"
      dimensions  = { outcome = "ok" }
    }
  }
```

The `ai_error` and `invalid_response` metric queries follow, identical except for `id` and the `outcome` dimension.

- The comment states why the alarm exists, which is the gap Task 3 closes. It also states the tradeoff: an OpenAI outage during a deploy rolls back a good release.
- `threshold = local.alarm_suggestion_failure_percent`: 7.2, a percent, because the expression multiplies by 100.
- `evaluation_periods = 1` and `datapoints_to_alarm = 1` with a 5-minute period: the short window of the burn-rate rule. CloudWatch has no second window in one alarm.
- `treat_missing_data = "notBreaching"`: no suggestion traffic, or a dead collector, is not an alarm. See [Limits](/observability-limits#open) for the cost of that choice.
- `metric_query "ratio"`: the failure percentage, and 0 below 10 requests in the period.
- `metric_query "failures"` and `"requests"`: sums of the per-outcome series, each `FILL`ed with 0, because a series has no datapoint until its first event. `bad_request` is in neither.
- `metric_query "ok"` and the two after it: `Patent/Server` `suggestions.requests` with one dimension, `outcome`. That is exactly what `aws.yaml` declares for the EMF exporter (`dimensions: [[outcome]]`, no rollups). If the dimensions differ, the alarm finds no metric and stays OK, so this is the first thing to check in a live account.

**Unhealthy hosts alarm — `aws_cloudwatch_metric_alarm.unhealthy_hosts`**

```hcl modules/service/alarms.tf
resource "aws_cloudwatch_metric_alarm" "unhealthy_hosts" {
  alarm_name          = "${var.name}-alb-unhealthy-hosts"
  alarm_description   = "At least one task fails the ALB health check."
  namespace           = "AWS/ApplicationELB"
  metric_name         = "UnHealthyHostCount"
  dimensions          = local.alarm_dimensions
  statistic           = "Maximum"
  period              = local.alarm_period_seconds
  comparison_operator = "GreaterThanThreshold"
  threshold           = 0
  evaluation_periods  = local.alarm_evaluation_periods
  datapoints_to_alarm = local.alarm_evaluation_periods
  treat_missing_data  = "notBreaching"
  alarm_actions       = [var.alarm_topic_arn]
  ok_actions          = [var.alarm_topic_arn]
  tags                = var.tags
}
```

- `alarm_name` and `alarm_description`: the description says what it means, at least one task fails the ALB health check.
- `namespace = "AWS/ApplicationELB"` and `metric_name = "UnHealthyHostCount"`: the number of targets failing health checks.
- `dimensions = local.alarm_dimensions`: this load balancer and target group.
- `statistic = "Maximum"`: the worst value in the period, so a single unhealthy task in any minute counts.
- `period = local.alarm_period_seconds`: one-minute periods.
- `comparison_operator = "GreaterThanThreshold"` and `threshold = 0`: any unhealthy host breaches.
- `evaluation_periods` and `datapoints_to_alarm`: three of three consecutive periods, which filters out a task that is replaced during a deploy or restart.
- `treat_missing_data = "notBreaching"`: missing data is not a failure.
- `alarm_actions`, `ok_actions` and `tags`: topic notifications on alarm and recovery, and standard tags.

**Response time alarm — `aws_cloudwatch_metric_alarm.response_time_p95`**

```hcl modules/service/alarms.tf
# Covers HTTP requests only: a WebSocket session lasts minutes and is not a response time.
resource "aws_cloudwatch_metric_alarm" "response_time_p95" {
  alarm_name          = "${var.name}-alb-target-response-time-p95"
  alarm_description   = "p95 target response time is above the threshold."
  namespace           = "AWS/ApplicationELB"
  metric_name         = "TargetResponseTime"
  dimensions          = local.alarm_dimensions
  extended_statistic  = "p95"
  period              = local.alarm_period_seconds
  comparison_operator = "GreaterThanThreshold"
  threshold           = local.alarm_p95_response_time_second
  evaluation_periods  = local.alarm_evaluation_periods
  datapoints_to_alarm = local.alarm_evaluation_periods
  treat_missing_data  = "notBreaching"
  alarm_actions       = [var.alarm_topic_arn]
  ok_actions          = [var.alarm_topic_arn]
  tags                = var.tags
}
```

- The comment limits the scope: it covers HTTP requests only. A WebSocket session lasts minutes and is not a response time.
- `alarm_name` and `alarm_description`: the description names the metric and the condition.
- `namespace = "AWS/ApplicationELB"` and `metric_name = "TargetResponseTime"`: seconds from the ALB forwarding a request to the task starting its response.
- `dimensions = local.alarm_dimensions`: this load balancer and target group.
- `extended_statistic = "p95"`: a percentile. CloudWatch takes percentiles through `extended_statistic`, not `statistic`. p95 reflects what slow users see, where an average hides them.
- `period`, `comparison_operator` and `threshold = local.alarm_p95_response_time_second`: fire when p95 exceeds 2 seconds.
- `evaluation_periods` and `datapoints_to_alarm`: three of three periods.
- `treat_missing_data`, `alarm_actions`, `ok_actions` and `tags`: as for the unhealthy hosts alarm.

#### variables.tf

**Task bound validation — `variable.max_tasks`**

```hcl modules/service/variables.tf
variable "max_tasks" {
  type        = number
  description = "Autoscaling upper bound."
  default     = 12

  validation {
    condition     = var.max_tasks >= var.min_tasks
    error_message = "max_tasks must be greater than or equal to min_tasks."
  }
}
```

- `type = number` and `default = 12`: the autoscaling ceiling when the caller does not set one.
- `validation { condition = var.max_tasks >= var.min_tasks }`: a variable validation may reference another variable. It rejects a ceiling below the floor at plan time, with the clear `error_message`. Without it, a bad pair of values would only surface at apply time.

## Edge

Needs two providers: the default `aws` and aws.us_east_1, because CloudFront only accepts its certificate and WAF web ACL from us-east-1.

- **Site bucket:** private, versioned and KMS-encrypted, read only through Origin Access Control.
- **CloudFront:** one distribution, with S3 as the default behaviour and the ALB as a VPC origin for `/api/*` and `/ws`. Those two behaviours have caching off and forward all viewer headers.
- **WAF:** AWS managed rule groups plus a per-IP rate limit.
- **Security:** a security response headers policy, and TLS 1.2 minimum.
- **DNS:** Route 53 alias records for the domain.

| Inputs | Outputs |
|---|---|
| `name`, `tags`, `domain_name`, `route53_zone_id`, `alb_arn`, `alb_dns_name`, `api_path_pattern`, `ws_path_pattern`, `waf_rate_limit`, `price_class` | `distribution_id`, `distribution_domain_name`, `site_bucket_name`, `site_bucket_arn`, `web_acl_arn` |

### Walkthrough

#### versions.tf

**Provider requirements — `required_providers`**

```hcl modules/edge/versions.tf
terraform {
  required_version = ">= 1.10"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
      # CloudFront certificates and CloudFront-scoped WAF must live in us-east-1.
      configuration_aliases = [aws.us_east_1]
    }
  }
}
```

- `required_version = ">= 1.10"`: minimum Terraform CLI version for the module.
- `required_providers { aws = { ... } }`: declares the AWS provider the module uses.
  - `source = "hashicorp/aws"`: the official provider.
  - `version = "~> 6.0"`: any 6.x release, blocking a major upgrade that could change resource schemas.
  - `configuration_aliases = [aws.us_east_1]`: declares that the module expects a second, aliased AWS provider configuration from its caller. A child module cannot create provider configurations itself; the root passes one in with `providers = { aws.us_east_1 = aws.us_east_1 }`. Resources here select it with `provider = aws.us_east_1`. Without this line, those references fail validation. CloudFront certificates and CloudFront-scope WAF web ACLs exist only in us-east-1, whatever region the rest of the stack uses.

#### site.tf

**Lookups and locals**

```hcl modules/edge/site.tf
data "aws_caller_identity" "current" {}
data "aws_partition" "current" {}

locals {
  site_bucket_name = "${var.name}-site-${data.aws_caller_identity.current.account_id}"
}
```

- `data "aws_caller_identity" "current"`: reads the account ID of the credentials Terraform runs with, so names and policies can refer to this account without a variable.
- `data "aws_partition" "current"`: reads the partition (`aws`, `aws-cn`, `aws-us-gov`) so ARNs built by hand are not hard-coded to `arn:aws`.
- `locals { site_bucket_name = ... }`: bucket name is `<name>-site-<account_id>`. S3 bucket names are global; the account ID makes a collision with another account unlikely. Bootstrap's IAM policies reference this exact pattern, so it must not change.

**Site key — `aws_kms_key.site`, `aws_kms_alias.site`**

```hcl modules/edge/site.tf
# --- Encryption key -------------------------------------------------------

resource "aws_kms_key" "site" {
  description = "${var.name} site bucket encryption"
  # Rotation is a baseline requirement for every customer-managed key.
  enable_key_rotation     = true
  deletion_window_in_days = 30
  tags                    = var.tags
}

resource "aws_kms_alias" "site" {
  name          = "alias/${var.name}-site"
  target_key_id = aws_kms_key.site.key_id
}
```

- `description`: shown in the KMS console; identifies which stack owns the key.
- `enable_key_rotation = true`: KMS rotates the key material yearly. New data uses new material and old ciphertext stays decryptable.
- `deletion_window_in_days = 30`: the longest waiting period KMS allows between a delete request and actual deletion, leaving the most time to cancel an accidental delete. Deleting the key would make every object in the bucket unreadable.
- `tags = var.tags`: applies the shared tag map passed by the caller. Every taggable resource in this module does the same.
- `aws_kms_alias.site`: gives the key the stable name `alias/${var.name}-site`. Bootstrap's IAM policies refer to this alias, so it must not change.
  - `target_key_id = aws_kms_key.site.key_id`: points the alias at the key.

**Key policy — `aws_iam_policy_document.site_key`, `aws_kms_key_policy.site`**

```hcl modules/edge/site.tf
# Separate resource so the key does not depend on the distribution at creation:
# key -> bucket -> distribution -> key policy (no cycle).
data "aws_iam_policy_document" "site_key" {
  # Standard statement: lets IAM policies delegate key use.
  statement {
    sid       = "EnableIamPolicies"
    actions   = ["kms:*"]
    resources = ["*"]
    principals {
      type        = "AWS"
      identifiers = ["arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:root"]
    }
  }

  # OAC reads SSE-KMS objects as the CloudFront service principal, scoped to this distribution.
  statement {
    sid       = "AllowCloudFrontServicePrincipalSSEKMS"
    actions   = ["kms:Decrypt", "kms:Encrypt", "kms:GenerateDataKey*"]
    resources = ["*"]
    principals {
      type        = "Service"
      identifiers = ["cloudfront.amazonaws.com"]
    }
    condition {
      test     = "StringEquals"
      variable = "AWS:SourceArn"
      values   = [aws_cloudfront_distribution.this.arn]
    }
  }
}

resource "aws_kms_key_policy" "site" {
  key_id = aws_kms_key.site.id
  policy = data.aws_iam_policy_document.site_key.json
}
```

- The comment explains the layout. The policy names `aws_cloudfront_distribution.this.arn`. The distribution depends on the bucket, and the bucket depends on the key (SSE-KMS). If the policy were inline in `aws_kms_key.site`, the key would depend on the distribution and Terraform would report a cycle. A separate `aws_kms_key_policy` resource is created last, which gives the chain key -> bucket -> distribution -> key policy.
- `data "aws_iam_policy_document" "site_key"`: builds the policy JSON in HCL instead of a hand-written string.
- First `statement`, `EnableIamPolicies`: the standard key-policy statement.
  - `sid = "EnableIamPolicies"`: label for the statement.
  - `actions = ["kms:*"]`, `resources = ["*"]`: all KMS actions; in a key policy `*` means this key.
  - `principals { type = "AWS" }` with `identifiers = [".../root"]`: the account root principal. This does not grant the root user alone; it delegates to IAM, so any IAM identity in the account with a `kms:` allow can use the key. Without it only the policy's named principals could, and the key could become unmanageable.
  - `arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:root`: builds the account ARN from the two lookups.
- Second `statement`, `AllowCloudFrontServicePrincipalSSEKMS`: lets CloudFront read encrypted objects.
  - `actions = ["kms:Decrypt", "kms:Encrypt", "kms:GenerateDataKey*"]`: Origin Access Control fetches objects as the CloudFront service principal, which needs `Decrypt` to read SSE-KMS objects. `Encrypt` and `GenerateDataKey*` are the other key actions the service may use against SSE-KMS objects.
  - `principals { type = "Service" }` with `identifiers = ["cloudfront.amazonaws.com"]`: the CloudFront service, not an account principal.
  - `condition` with `test = "StringEquals"`, `variable = "AWS:SourceArn"`, `values = [distribution ARN]`: only this distribution may use the key. Without it any CloudFront distribution in any account would match the service principal (confused-deputy risk).
- `aws_kms_key_policy.site`: attaches the policy to the key.
  - `key_id = aws_kms_key.site.id`: the key to attach to.
  - `policy = data.aws_iam_policy_document.site_key.json`: the rendered JSON.

**Bucket — `aws_s3_bucket.site` and ownership controls**

```hcl modules/edge/site.tf
# --- Bucket ---------------------------------------------------------------

resource "aws_s3_bucket" "site" {
  bucket = local.site_bucket_name
  tags   = var.tags
}

# Disables ACLs entirely; the bucket policy is the only access path.
resource "aws_s3_bucket_ownership_controls" "site" {
  bucket = aws_s3_bucket.site.id
  rule {
    object_ownership = "BucketOwnerEnforced"
  }
}
```

- `bucket = local.site_bucket_name`: the account-scoped name from the locals.
- `tags = var.tags`: standard tags.
- `aws_s3_bucket_ownership_controls.site`: sets who owns uploaded objects.
  - `bucket = aws_s3_bucket.site.id`: attaches to the bucket. Referencing the resource also orders creation.
  - `rule { object_ownership = "BucketOwnerEnforced" }`: disables ACLs. The bucket owner owns every object regardless of uploader, and the bucket policy is the only access path.

**Public access block — `aws_s3_bucket_public_access_block.site`**

```hcl modules/edge/site.tf
resource "aws_s3_bucket_public_access_block" "site" {
  bucket                  = aws_s3_bucket.site.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}
```

- `bucket`: the bucket to protect.
- `block_public_acls = true`: rejects requests that set a public ACL.
- `block_public_policy = true`: rejects a bucket policy that would grant public access.
- `ignore_public_acls = true`: ignores any public ACL that already exists.
- `restrict_public_buckets = true`: limits a bucket with a public policy to AWS service principals and authorised users.
- All four are on, so the bucket cannot become public by mistake; content is reachable only through CloudFront.

**Versioning — `aws_s3_bucket_versioning.site`**

```hcl modules/edge/site.tf
# Versioning lets a bad client deploy be rolled back.
resource "aws_s3_bucket_versioning" "site" {
  bucket = aws_s3_bucket.site.id
  versioning_configuration {
    status = "Enabled"
  }
}
```

- The comment gives the reason: keeping prior object versions allows rolling back a bad client deploy.
- `bucket`: the bucket to configure.
- `versioning_configuration { status = "Enabled" }`: every overwrite or delete keeps the old version as a noncurrent version.

**Encryption — `aws_s3_bucket_server_side_encryption_configuration.site`**

```hcl modules/edge/site.tf
resource "aws_s3_bucket_server_side_encryption_configuration" "site" {
  bucket = aws_s3_bucket.site.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm     = "aws:kms"
      kms_master_key_id = aws_kms_key.site.arn
    }
    # Cuts KMS request cost and latency.
    bucket_key_enabled = true
  }
}
```

- `bucket`: the bucket to configure.
- `rule`: the default encryption rule for new objects.
  - `apply_server_side_encryption_by_default`: the default applied when an upload does not specify encryption.
    - `sse_algorithm = "aws:kms"`: encrypt with KMS instead of S3-managed keys, so key use is controlled by the key policy and logged in CloudTrail.
    - `kms_master_key_id = aws_kms_key.site.arn`: the customer-managed key from this file.
  - `bucket_key_enabled = true`: S3 uses a bucket-level key derived from the KMS key rather than calling KMS for each object. This cuts KMS request cost and latency.

**Lifecycle — `aws_s3_bucket_lifecycle_configuration.site`**

```hcl modules/edge/site.tf
# Versioned deploys would otherwise accumulate old client builds forever.
resource "aws_s3_bucket_lifecycle_configuration" "site" {
  bucket = aws_s3_bucket.site.id

  rule {
    id     = "expire-noncurrent-versions"
    status = "Enabled"
    filter {}
    noncurrent_version_expiration {
      noncurrent_days = 90
    }
    abort_incomplete_multipart_upload {
      days_after_initiation = 7
    }
  }

  depends_on = [aws_s3_bucket_versioning.site]
}
```

- The comment gives the reason: with versioning on, each deploy leaves old builds that would otherwise accumulate forever.
- `bucket`: the bucket to configure.
- `rule`: a single rule.
  - `id = "expire-noncurrent-versions"`: rule name.
  - `status = "Enabled"`: the rule is active.
  - `filter {}`: an empty filter applies the rule to every object. The provider expects a `filter` or `prefix` to be present.
  - `noncurrent_version_expiration { noncurrent_days = 90 }`: permanently deletes a version 90 days after it stops being current. That window is the rollback horizon.
  - `abort_incomplete_multipart_upload { days_after_initiation = 7 }`: removes parts of multipart uploads not completed within 7 days, which would otherwise be billed as storage.
- `depends_on = [aws_s3_bucket_versioning.site]`: noncurrent-version rules need versioning in place. There is no attribute reference between the two resources, so the ordering is stated explicitly.

**Bucket policy — `aws_iam_policy_document.site_bucket`, `aws_s3_bucket_policy.site`**

```hcl modules/edge/site.tf
data "aws_iam_policy_document" "site_bucket" {
  statement {
    sid       = "AllowCloudFrontRead"
    actions   = ["s3:GetObject"]
    resources = ["${aws_s3_bucket.site.arn}/*"]
    principals {
      type        = "Service"
      identifiers = ["cloudfront.amazonaws.com"]
    }
    condition {
      test     = "StringEquals"
      variable = "AWS:SourceArn"
      values   = [aws_cloudfront_distribution.this.arn]
    }
  }

  statement {
    sid       = "DenyInsecureTransport"
    effect    = "Deny"
    actions   = ["s3:*"]
    resources = [aws_s3_bucket.site.arn, "${aws_s3_bucket.site.arn}/*"]
    principals {
      type        = "*"
      identifiers = ["*"]
    }
    condition {
      test     = "Bool"
      variable = "aws:SecureTransport"
      values   = ["false"]
    }
  }
}

resource "aws_s3_bucket_policy" "site" {
  bucket = aws_s3_bucket.site.id
  policy = data.aws_iam_policy_document.site_bucket.json

  depends_on = [aws_s3_bucket_public_access_block.site]
}
```

- First `statement`, `AllowCloudFrontRead`: the only allow in the policy.
  - `actions = ["s3:GetObject"]`: read objects only; no list, write or delete.
  - `resources = ["${aws_s3_bucket.site.arn}/*"]`: objects in the bucket, not the bucket itself.
  - `principals { type = "Service" }` with `identifiers = ["cloudfront.amazonaws.com"]`: the CloudFront service. This is how Origin Access Control authenticates (see `aws_cloudfront_origin_access_control.site` below).
  - `condition` on `AWS:SourceArn` with the distribution ARN: restricts the grant to this distribution, so other distributions cannot read the bucket. The distribution ARN reference makes this policy depend on the distribution.
- Second `statement`, `DenyInsecureTransport`: enforces TLS.
  - `effect = "Deny"`: statements default to `Allow`; this one overrides.
  - `actions = ["s3:*"]`: every S3 action.
  - `resources`: both the bucket ARN and the `/*` object ARN, so bucket-level and object-level calls are covered.
  - `principals { type = "*", identifiers = ["*"] }`: everyone.
  - `condition` with `test = "Bool"`, `variable = "aws:SecureTransport"`, `values = ["false"]`: matches requests made over plain HTTP.
- `aws_s3_bucket_policy.site`: attaches the policy.
  - `bucket`, `policy`: target bucket and rendered JSON.
  - `depends_on = [aws_s3_bucket_public_access_block.site]`: applying the policy and the public access block at the same time can fail with a conflicting-operation error. Waiting for the block avoids it.

#### waf.tf

**Managed rule groups — `local.waf_managed_groups`**

```hcl modules/edge/waf.tf
locals {
  # Managed groups in evaluation order; the rate rule follows them.
  waf_managed_groups = {
    AWSManagedRulesCommonRuleSet          = 10
    AWSManagedRulesKnownBadInputsRuleSet  = 20
    AWSManagedRulesAmazonIpReputationList = 30
  }
}
```

- `waf_managed_groups`: a map of AWS managed rule group name to priority. It drives the `dynamic "rule"` block in the web ACL, so adding a group is one line.
- `AWSManagedRulesCommonRuleSet = 10`: baseline protections against common web exploits (OWASP-style).
- `AWSManagedRulesKnownBadInputsRuleSet = 20`: blocks request patterns known to exploit vulnerabilities.
- `AWSManagedRulesAmazonIpReputationList = 30`: blocks IPs AWS has flagged.
- Priorities set evaluation order, lowest first, and must be unique within the ACL. The gaps of 10 leave room to insert rules. The rate rule uses 40, after these.

**Web ACL — `aws_wafv2_web_acl.this`**

```hcl modules/edge/waf.tf
resource "aws_wafv2_web_acl" "this" {
  provider = aws.us_east_1

  name        = "${var.name}-web-acl"
  description = "Edge protection for ${var.domain_name}"
  # CLOUDFRONT scope only exists in us-east-1.
  scope = "CLOUDFRONT"

  default_action {
    allow {}
  }

  dynamic "rule" {
    for_each = local.waf_managed_groups

    content {
      name     = rule.key
      priority = rule.value

      # "none" keeps each managed rule's own action.
      override_action {
        none {}
      }

      statement {
        managed_rule_group_statement {
          name        = rule.key
          vendor_name = "AWS"

          dynamic "rule_action_override" {
            for_each = rule.key == "AWSManagedRulesCommonRuleSet" ? ["SizeRestrictions_BODY"] : []

            content {
              name = rule_action_override.value
              # POST /save/{id} sends a whole patent document, far above the 8 KB limit of
              # SizeRestrictions_BODY; count it instead of blocking legitimate saves.
              action_to_use {
                count {}
              }
            }
          }
        }
      }

      visibility_config {
        cloudwatch_metrics_enabled = true
        sampled_requests_enabled   = true
        metric_name                = "${var.name}-${rule.key}"
      }
    }
  }

  rule {
    name     = "rate-limit-per-ip"
    priority = 40

    action {
      block {}
    }

    statement {
      rate_based_statement {
        limit              = var.waf_rate_limit
        aggregate_key_type = "IP"
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      sampled_requests_enabled   = true
      metric_name                = "${var.name}-rate-limit-per-ip"
    }
  }

  visibility_config {
    cloudwatch_metrics_enabled = true
    sampled_requests_enabled   = true
    metric_name                = "${var.name}-web-acl"
  }

  tags = var.tags
}
```

- `provider = aws.us_east_1`: creates the ACL in us-east-1 through the aliased provider declared in `versions.tf`.
- `name`, `description`: `${var.name}`-prefixed name and a description that includes `var.domain_name`.
- `scope = "CLOUDFRONT"`: makes the ACL attachable to a CloudFront distribution. This scope exists only in us-east-1, hence the provider.
- `default_action { allow {} }`: traffic that matches no blocking rule is allowed. The ACL is a deny-list of bad traffic, not an allow-list.
- `dynamic "rule"`: generates one `rule` block per entry in `local.waf_managed_groups`.
  - `for_each = local.waf_managed_groups`: each iteration exposes `rule.key` (group name) and `rule.value` (priority).
  - `content`: the body of each generated rule.
    - `name = rule.key`, `priority = rule.value`: the rule is named after the group and ordered by the map value.
    - `override_action { none {} }`: managed rule groups use `override_action`, not `action`. `none` leaves each rule inside the group on its own action (block for most); `count` here would turn the whole group into monitoring only.
    - `statement { managed_rule_group_statement { ... } }`: runs a managed group.
      - `name = rule.key`, `vendor_name = "AWS"`: selects the AWS group.
      - `dynamic "rule_action_override"`: changes the action of individual rules inside a group.
        - `for_each = rule.key == "AWSManagedRulesCommonRuleSet" ? ["SizeRestrictions_BODY"] : []`: a conditional list. For the common rule set it holds one rule name and the block is generated once; for the other two groups the list is empty and no override is generated. This avoids repeating the whole rule block just to add one override.
        - `name = rule_action_override.value`: the rule inside the group to override, here `SizeRestrictions_BODY`.
        - `action_to_use { count {} }`: counts the match (visible in metrics and sampled requests) instead of blocking. The comment gives the cause: `POST /save/{id}` sends a whole patent document, far above the 8 KB limit of `SizeRestrictions_BODY`, so the default block action would reject legitimate saves. The other common rules still apply.
    - `visibility_config`: observability for the rule.
      - `cloudwatch_metrics_enabled = true`: publishes CloudWatch metrics for the rule.
      - `sampled_requests_enabled = true`: stores a sample of matching requests for inspection in the console.
      - `metric_name = "${var.name}-${rule.key}"`: unique metric name per rule.
- `rule` (rate limit): a plain rule after the managed groups.
  - `name = "rate-limit-per-ip"`, `priority = 40`: follows priority 30, the last managed group.
  - `action { block {} }`: a normal rule uses `action`; matching requests are blocked.
  - `statement { rate_based_statement { ... } }`: counts requests per key.
    - `limit = var.waf_rate_limit`: maximum requests in the 5-minute evaluation window before blocking.
    - `aggregate_key_type = "IP"`: counts per client IP address.
  - `visibility_config`: same three arguments as above, with metric name `${var.name}-rate-limit-per-ip`.
- `visibility_config` (ACL level): metrics and sampling for the ACL as a whole, with metric name `${var.name}-web-acl`. WAFv2 requires it on the ACL as well as on each rule.
- `tags = var.tags`: standard tags.

#### main.tf

**Managed policies and locals — `data.aws_cloudfront_*`, `local.*_origin_id`**

```hcl modules/edge/main.tf
data "aws_cloudfront_cache_policy" "caching_optimized" {
  name = "Managed-CachingOptimized"
}

data "aws_cloudfront_cache_policy" "caching_disabled" {
  name = "Managed-CachingDisabled"
}

# AllViewer forwards every viewer header including Host and Sec-WebSocket-*; the ALB certificate
# is issued for domain_name, so the Host header must reach the origin for TLS validation to pass.
data "aws_cloudfront_origin_request_policy" "all_viewer" {
  name = "Managed-AllViewer"
}

locals {
  s3_origin_id  = "site-bucket"
  alb_origin_id = "alb"
}
```

- `data "aws_cloudfront_cache_policy" "caching_optimized"`: looks up the AWS-managed `Managed-CachingOptimized` policy by name. It caches by URL and respects compression; used for static files from S3.
- `data "aws_cloudfront_cache_policy" "caching_disabled"`: looks up `Managed-CachingDisabled`, which turns caching off. Used for the API and WebSocket paths, where responses are per-user or live.
- `data "aws_cloudfront_origin_request_policy" "all_viewer"`: looks up `Managed-AllViewer`. The comment gives the reason: it forwards every viewer header, including `Host` and `Sec-WebSocket-*`. The ALB certificate is issued for `domain_name`, so CloudFront must send that `Host` for TLS validation to pass, and the WebSocket handshake needs its headers to reach the server.
- `locals`: two string IDs, `s3_origin_id` and `alb_origin_id`, defined once so the origin blocks and behaviours refer to the same labels.

**Origin access control — `aws_cloudfront_origin_access_control.site`**

```hcl modules/edge/main.tf
resource "aws_cloudfront_origin_access_control" "site" {
  name                              = "${var.name}-site"
  description                       = "Signed access to the ${var.name} site bucket"
  origin_access_control_origin_type = "s3"
  signing_behavior                  = "always"
  signing_protocol                  = "sigv4"
}
```

- `name = "${var.name}-site"`: `var.name` prefix keeps names unique per environment.
- `description`: free text naming the bucket this control serves.
- `origin_access_control_origin_type = "s3"`: the origin is an S3 bucket.
- `signing_behavior = "always"`: CloudFront signs every request to the origin, overriding any `Authorization` header from the viewer.
- `signing_protocol = "sigv4"`: the only supported protocol. The bucket policy in `site.tf` trusts the resulting signed requests from this distribution.

**VPC origin — `aws_cloudfront_vpc_origin.alb`**

```hcl modules/edge/main.tf
resource "aws_cloudfront_vpc_origin" "alb" {
  vpc_origin_endpoint_config {
    name                   = "${var.name}-alb"
    arn                    = var.alb_arn
    http_port              = 80
    https_port             = 443
    origin_protocol_policy = "https-only"

    origin_ssl_protocols {
      items    = ["TLSv1.2"]
      quantity = 1
    }
  }

  tags = var.tags
}
```

- A VPC origin lets CloudFront reach the internal ALB over AWS-managed network paths, so the ALB needs no public IP or internet-facing listener.
- `vpc_origin_endpoint_config`: the single required block.
  - `name = "${var.name}-alb"`: name of the VPC origin.
  - `arn = var.alb_arn`: the ALB to attach to. Its security group must admit CloudFront; the service module owns that rule (`alb_https_from_cloudfront`).
  - `http_port = 80`, `https_port = 443`: ports the origin accepts; both are required by the API even though only HTTPS is used.
  - `origin_protocol_policy = "https-only"`: CloudFront connects over TLS only. The ALB has a certificate for `domain_name`, so the connection is validated end to end.
  - `origin_ssl_protocols`: the TLS versions CloudFront may use to the origin.
    - `items = ["TLSv1.2"]`: TLS 1.2 only.
    - `quantity = 1`: the API requires the count alongside the list; it must equal the number of items.
- `tags = var.tags`: standard tags.

**Security headers — `aws_cloudfront_response_headers_policy.security`**

```hcl modules/edge/main.tf
resource "aws_cloudfront_response_headers_policy" "security" {
  name    = "${var.name}-security-headers"
  comment = "Security headers for ${var.domain_name}"

  security_headers_config {
    strict_transport_security {
      access_control_max_age_sec = 63072000
      include_subdomains         = true
      # Preload is a commitment for the whole registered domain; leave it to the domain owner.
      preload  = false
      override = true
    }
    content_type_options {
      override = true
    }
    frame_options {
      frame_option = "DENY"
      override     = true
    }
    referrer_policy {
      referrer_policy = "strict-origin-when-cross-origin"
      override        = true
    }
  }

  # Policy must be replaced before it is destroyed because the distribution references it.
  lifecycle {
    create_before_destroy = true
  }
}
```

- `name = "${var.name}-security-headers"`, `comment`: name and description mentioning the domain.
- `security_headers_config`: headers CloudFront adds to responses.
  - `strict_transport_security`: sets `Strict-Transport-Security`.
    - `access_control_max_age_sec = 63072000`: two years, in seconds.
    - `include_subdomains = true`: applies to subdomains too.
    - `preload = false`: the comment explains that preload is a commitment for the whole registered domain, so it is left to the domain owner.
    - `override = true`: CloudFront's value replaces one set by the origin.
  - `content_type_options { override = true }`: sets `X-Content-Type-Options: nosniff`, stopping browsers from guessing MIME types.
  - `frame_options`: `frame_option = "DENY"` sets `X-Frame-Options: DENY`, so the app cannot be embedded in a frame (clickjacking). `override = true` replaces any origin value.
  - `referrer_policy`: `referrer_policy = "strict-origin-when-cross-origin"` sends the full URL for same-origin requests and only the origin cross-site, and nothing on downgrade to HTTP. `override = true` as above.
- `lifecycle { create_before_destroy = true }`: the comment gives the reason. The distribution references this policy, so a replacement must exist before the old one is deleted, or the delete fails while it is still in use.

**Distribution — `aws_cloudfront_distribution.this`**

```hcl modules/edge/main.tf
resource "aws_cloudfront_distribution" "this" {
  enabled             = true
  is_ipv6_enabled     = true
  http_version        = "http2and3"
  comment             = "${var.name} web app"
  default_root_object = "index.html"
  aliases             = [var.domain_name]
  price_class         = var.price_class
  web_acl_id          = aws_wafv2_web_acl.this.arn

  origin {
    origin_id                = local.s3_origin_id
    domain_name              = aws_s3_bucket.site.bucket_regional_domain_name
    origin_access_control_id = aws_cloudfront_origin_access_control.site.id
  }

  origin {
    origin_id   = local.alb_origin_id
    domain_name = var.alb_dns_name

    vpc_origin_config {
      vpc_origin_id = aws_cloudfront_vpc_origin.alb.id
      # Applies to HTTP API calls (60 s is the default quota maximum); the HTTP routes do not call
      # OpenAI. WebSockets are governed by CloudFront's separate, fixed 10-minute idle timeout.
      origin_read_timeout      = 60
      origin_keepalive_timeout = 60
    }
  }

  default_cache_behavior {
    target_origin_id           = local.s3_origin_id
    viewer_protocol_policy     = "redirect-to-https"
    allowed_methods            = ["GET", "HEAD", "OPTIONS"]
    cached_methods             = ["GET", "HEAD"]
    compress                   = true
    cache_policy_id            = data.aws_cloudfront_cache_policy.caching_optimized.id
    response_headers_policy_id = aws_cloudfront_response_headers_policy.security.id
  }

  ordered_cache_behavior {
    path_pattern               = var.api_path_pattern
    target_origin_id           = local.alb_origin_id
    viewer_protocol_policy     = "https-only"
    allowed_methods            = ["GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"]
    cached_methods             = ["GET", "HEAD"]
    cache_policy_id            = data.aws_cloudfront_cache_policy.caching_disabled.id
    origin_request_policy_id   = data.aws_cloudfront_origin_request_policy.all_viewer.id
    response_headers_policy_id = aws_cloudfront_response_headers_policy.security.id
  }

  # The WebSocket upgrade is a GET; no other method is needed.
  ordered_cache_behavior {
    path_pattern               = var.ws_path_pattern
    target_origin_id           = local.alb_origin_id
    viewer_protocol_policy     = "https-only"
    allowed_methods            = ["GET", "HEAD", "OPTIONS"]
    cached_methods             = ["GET", "HEAD"]
    cache_policy_id            = data.aws_cloudfront_cache_policy.caching_disabled.id
    origin_request_policy_id   = data.aws_cloudfront_origin_request_policy.all_viewer.id
    response_headers_policy_id = aws_cloudfront_response_headers_policy.security.id
  }

  viewer_certificate {
    acm_certificate_arn      = aws_acm_certificate_validation.cloudfront.certificate_arn
    ssl_support_method       = "sni-only"
    minimum_protocol_version = "TLSv1.2_2021"
  }

  restrictions {
    geo_restriction {
      restriction_type = "none"
    }
  }

  tags = var.tags
}
```

- `enabled = true`: the distribution serves traffic.
- `is_ipv6_enabled = true`: answers over IPv6; the `AAAA` alias record in `dns.tf` relies on it.
- `http_version = "http2and3"`: viewers can use HTTP/2 and HTTP/3.
- `comment`: description in the console.
- `default_root_object = "index.html"`: a request for `/` returns `index.html` from the bucket.
- `aliases = [var.domain_name]`: the custom domain the distribution answers for. It must be covered by the viewer certificate.
- `price_class = var.price_class`: edge locations used; defaults to `PriceClass_All`, the broadest and most expensive set.
- `web_acl_id = aws_wafv2_web_acl.this.arn`: attaches the WAF ACL from `waf.tf`.
- First `origin` (S3):
  - `origin_id = local.s3_origin_id`: label used by behaviours.
  - `domain_name = aws_s3_bucket.site.bucket_regional_domain_name`: the regional bucket endpoint, which CloudFront's S3 origin with OAC expects. The global endpoint can answer a new bucket with redirects.
  - `origin_access_control_id`: signs requests with the OAC above; the bucket has no public path.
- Second `origin` (ALB):
  - `origin_id = local.alb_origin_id`: label for behaviours.
  - `domain_name = var.alb_dns_name`: the ALB DNS name. CloudFront sends it as `Host` unless the origin request policy forwards the viewer's.
  - `vpc_origin_config`: routes the connection through the VPC origin instead of the public internet.
    - `vpc_origin_id = aws_cloudfront_vpc_origin.alb.id`: the VPC origin defined above.
    - `origin_read_timeout = 60`: seconds CloudFront waits for a response. The comment notes 60 is the default quota maximum, and the HTTP routes do not call OpenAI. WebSockets are governed by CloudFront's separate, fixed 10-minute idle timeout.
    - `origin_keepalive_timeout = 60`: seconds an idle connection to the origin is kept open for reuse.
- `default_cache_behavior`: handles every path not matched by an ordered behaviour, so the SPA and static assets come from S3.
  - `target_origin_id = local.s3_origin_id`: send to the bucket.
  - `viewer_protocol_policy = "redirect-to-https"`: HTTP requests get a redirect to HTTPS.
  - `allowed_methods = ["GET", "HEAD", "OPTIONS"]`: read-only methods, enough for static files.
  - `cached_methods = ["GET", "HEAD"]`: methods whose responses are cached.
  - `compress = true`: compresses text assets at the edge.
  - `cache_policy_id`: `Managed-CachingOptimized`.
  - `response_headers_policy_id`: the security headers policy.
- First `ordered_cache_behavior` (API): evaluated before the default, in file order.
  - `path_pattern = var.api_path_pattern`: `/api/*` by default.
  - `target_origin_id = local.alb_origin_id`: send to the ALB through the VPC origin.
  - `viewer_protocol_policy = "https-only"`: plain HTTP is rejected, not redirected, since API clients should not use HTTP at all.
  - `allowed_methods`: all seven methods, so writes such as `POST /save/{id}` are proxied.
  - `cached_methods = ["GET", "HEAD"]`: required argument; with caching disabled nothing is stored.
  - `cache_policy_id`: `Managed-CachingDisabled`, so every call reaches the server.
  - `origin_request_policy_id`: `Managed-AllViewer`, forwarding headers, cookies and query strings.
  - `response_headers_policy_id`: the same security headers.
- Second `ordered_cache_behavior` (WebSocket): same shape as the API behaviour.
  - `path_pattern = var.ws_path_pattern`: `/ws` by default.
  - `allowed_methods = ["GET", "HEAD", "OPTIONS"]`: the comment explains the WebSocket upgrade is a GET, so write methods are not exposed on this path.
  - The remaining arguments match the API behaviour: ALB origin, HTTPS only, no caching, all viewer headers (which carries `Sec-WebSocket-*`), security headers.
- `viewer_certificate`: TLS for viewers.
  - `acm_certificate_arn = aws_acm_certificate_validation.cloudfront.certificate_arn`: uses the validated us-east-1 certificate from `dns.tf`. Referencing the validation resource makes the distribution wait until the certificate is issued.
  - `ssl_support_method = "sni-only"`: SNI instead of dedicated IPs, which carry a monthly fee and are only needed by very old clients.
  - `minimum_protocol_version = "TLSv1.2_2021"`: rejects TLS 1.1 and older and uses a modern cipher set.
- `restrictions { geo_restriction { restriction_type = "none" } }`: no country allow or block list. The block is required.
- `tags = var.tags`: standard tags.

#### dns.tf

**Certificate — `aws_acm_certificate.cloudfront`**

```hcl modules/edge/dns.tf
resource "aws_acm_certificate" "cloudfront" {
  provider = aws.us_east_1

  domain_name = var.domain_name
  # CloudFront only accepts certificates from us-east-1.
  validation_method = "DNS"
  tags              = var.tags

  lifecycle {
    create_before_destroy = true
  }
}
```

- `provider = aws.us_east_1`: CloudFront only accepts certificates from us-east-1 (see the comment).
- `domain_name = var.domain_name`: the single name the certificate covers.
- `validation_method = "DNS"`: ACM proves ownership through a CNAME record, which Terraform creates next. It needs no manual step and renews automatically while the record stays.
- `tags = var.tags`: standard tags.
- `lifecycle { create_before_destroy = true }`: when the certificate must be replaced, the new one is issued before the old one is removed. The distribution is still using the old one, and ACM refuses to delete a certificate in use.

**Validation record — `aws_route53_record.cert_validation`**

```hcl modules/edge/dns.tf
resource "aws_route53_record" "cert_validation" {
  for_each = {
    for o in aws_acm_certificate.cloudfront.domain_validation_options : o.domain_name => {
      name   = o.resource_record_name
      type   = o.resource_record_type
      record = o.resource_record_value
    }
  }

  zone_id = var.route53_zone_id
  name    = each.value.name
  type    = each.value.type
  records = [each.value.record]
  ttl     = 60
  # The service module validates the same name for the regional certificate; the record is identical.
  allow_overwrite = true
}
```

- `for_each = { for o in ...domain_validation_options : o.domain_name => {...} }`: ACM reports, per domain on the certificate, the record it expects. The expression turns that set into a map keyed by domain name. A key known at plan time is needed because the option values are only known after the certificate exists.
  - `name = o.resource_record_name`, `type = o.resource_record_type`, `record = o.resource_record_value`: the record ACM wants, a CNAME.
- `zone_id = var.route53_zone_id`: the public hosted zone that holds the domain.
- `name`, `type`: from `each.value`.
- `records = [each.value.record]`: the record value, as a one-item list.
- `ttl = 60`: one minute, so a corrected record propagates quickly.
- `allow_overwrite = true`: the comment explains that the service module validates the same name for its regional certificate and the record is identical. ACM generates the same validation CNAME for the same domain in one account, so without overwrite the second module to apply would fail because the record already exists.

**Certificate validation — `aws_acm_certificate_validation.cloudfront`**

```hcl modules/edge/dns.tf
resource "aws_acm_certificate_validation" "cloudfront" {
  provider = aws.us_east_1

  certificate_arn         = aws_acm_certificate.cloudfront.arn
  validation_record_fqdns = [for r in aws_route53_record.cert_validation : r.fqdn]
}
```

- `provider = aws.us_east_1`: must match the certificate's region.
- `certificate_arn = aws_acm_certificate.cloudfront.arn`: the certificate to wait on.
- `validation_record_fqdns = [for r in aws_route53_record.cert_validation : r.fqdn]`: the records that prove ownership. This resource creates nothing; it blocks until ACM reports the certificate issued, and the distribution references its output so it is not created with a pending certificate.

**Alias records — `aws_route53_record.alias`**

```hcl modules/edge/dns.tf
resource "aws_route53_record" "alias" {
  for_each = toset(["A", "AAAA"])

  zone_id = var.route53_zone_id
  name    = var.domain_name
  type    = each.value

  alias {
    name                   = aws_cloudfront_distribution.this.domain_name
    zone_id                = aws_cloudfront_distribution.this.hosted_zone_id
    evaluate_target_health = false
  }
}
```

- `for_each = toset(["A", "AAAA"])`: creates one record per type, so IPv4 and IPv6 clients both resolve the name. This matches `is_ipv6_enabled = true` on the distribution.
- `zone_id = var.route53_zone_id`, `name = var.domain_name`: the zone and name of the record.
- `type = each.value`: `A` or `AAAA`.
- `alias`: a Route 53 alias, which points at an AWS resource instead of an IP and cannot be created as a plain CNAME at a zone apex.
  - `name = aws_cloudfront_distribution.this.domain_name`: the `*.cloudfront.net` name.
  - `zone_id = aws_cloudfront_distribution.this.hosted_zone_id`: CloudFront's hosted zone ID, which Route 53 needs to resolve the alias.
  - `evaluate_target_health = false`: CloudFront has no health to evaluate for alias purposes; there is no failover here.

## Bootstrap

A root stack with local state, applied once per account. It creates:

- **State bucket:** KMS-encrypted, versioned, public access blocked, TLS-only.
- **GitHub access:** the GitHub OIDC provider and the deploy, plan and apply roles described on [Deployment](/deployment#github-roles).

| Inputs | Outputs |
|---|---|
| `name`, `tags`, `aws_region`, `github_repository`, `github_environment` | `state_bucket_name`, `oidc_provider_arn`, `deploy_role_arn`, `terraform_plan_role_arn`, `terraform_apply_role_arn`, `backend_config` |

:::warning[Fixed resource names]
Bootstrap runs before the environment exists, so its IAM policies refer to resources by name. These names must not change:

| Resource | Name |
|---|---|
| ECR repository, ECS service, task definition family | `${name}-server` |
| ECS cluster | `${name}-cluster` |
| Task execution role | `${name}-task-execution` |
| Task role | `${name}-task` |
| Site bucket | `${name}-site-<account_id>` |
| Site bucket KMS alias | `alias/${name}-site` |
:::

### Walkthrough

#### main.tf

**Provider, lookups and locals**

```hcl bootstrap/main.tf
provider "aws" {
  region = var.aws_region

  default_tags {
    tags = var.tags
  }
}

data "aws_caller_identity" "current" {}
data "aws_partition" "current" {}
data "aws_region" "current" {}

locals {
  account_id = data.aws_caller_identity.current.account_id
  partition  = data.aws_partition.current.partition
  region     = data.aws_region.current.region

  state_bucket_name = "${var.name}-tfstate-${local.account_id}"
}
```

- `provider "aws"`: bootstrap is a root stack, so it configures the provider itself. The modules never do; they inherit the provider from whichever root stack calls them.
- `region = var.aws_region`: the region of the state bucket, its KMS key and the application environment. There is no default, so the region is always chosen explicitly.
- `default_tags { tags = var.tags }`: the provider stamps `var.tags` on every taggable resource in this stack. Modules cannot do this, so they take `tags` and apply it themselves; here the resources need no `tags` argument.
- `data "aws_caller_identity" "current"`: reads the account ID of the credentials Terraform runs with, so ARNs and the bucket name can include it without a variable.
- `data "aws_partition" "current"`: returns `aws`, `aws-cn` or `aws-us-gov`, so ARNs written as strings stay valid outside the commercial partition.
- `data "aws_region" "current"`: reads the region the provider is using, which is `var.aws_region`.
- `account_id`, `partition`, `region`: short aliases for the three lookups, used in ARN strings through both files.
- `state_bucket_name = "${var.name}-tfstate-${local.account_id}"`: S3 bucket names are global. The account ID suffix makes a collision with another account's bucket unlikely and makes the owner obvious.

**State key — `aws_kms_key.state`**

```hcl bootstrap/main.tf
data "aws_iam_policy_document" "state_key" {
  # Standard statement: lets IAM policies (the roles below, operators) delegate key use.
  statement {
    sid       = "EnableIamPolicies"
    effect    = "Allow"
    actions   = ["kms:*"]
    resources = ["*"]

    principals {
      type        = "AWS"
      identifiers = ["arn:${local.partition}:iam::${local.account_id}:root"]
    }
  }
}

resource "aws_kms_key" "state" {
  description = "${var.name} Terraform state encryption"
  policy      = data.aws_iam_policy_document.state_key.json

  # Rotation is a baseline control for every customer-managed key.
  enable_key_rotation = true

  # Longest allowed window: losing this key makes every state file unreadable.
  deletion_window_in_days = 30
}

resource "aws_kms_alias" "state" {
  name          = "alias/${var.name}-tfstate"
  target_key_id = aws_kms_key.state.key_id
}
```

- `data "aws_iam_policy_document" "state_key"`: builds the key policy as HCL instead of a JSON string.
- `sid = "EnableIamPolicies"`, `effect = "Allow"`: the standard statement that lets IAM policies in the account grant key access. Without it only the key policy could grant access, and the roles below would not be able to use the key through their own policies.
- `actions = ["kms:*"]`, `resources = ["*"]`: in a key policy `*` means this key only. Access is then bounded by the IAM policies attached to principals.
- `principals { type = "AWS" ... }`: the account root principal. It does not mean the root user; it delegates to IAM in this account.
- `aws_kms_key.state`: customer-managed key for state encryption.
- `description`: names the key's purpose in the console and in CloudTrail.
- `policy = data.aws_iam_policy_document.state_key.json`: attaches the policy above.
- `enable_key_rotation = true`: AWS rotates the key material yearly. Old material is kept, so existing state objects still decrypt.
- `deletion_window_in_days = 30`: the longest allowed waiting period after a delete request. Deleting the key makes every state file unreadable, so the window is a chance to cancel.
- `aws_kms_alias.state`: a readable name, `alias/${var.name}-tfstate`, that points at the key through `target_key_id`. The alias is for people; the bucket and policies reference the key ARN.

**Bucket and hardening — `aws_s3_bucket.state`**

```hcl bootstrap/main.tf
resource "aws_s3_bucket" "state" {
  bucket = local.state_bucket_name

  # Destroying this bucket destroys the record of everything Terraform manages.
  lifecycle {
    prevent_destroy = true
  }
}

resource "aws_s3_bucket_ownership_controls" "state" {
  bucket = aws_s3_bucket.state.id

  # Disables ACLs, so only IAM and the bucket policy grant access.
  rule {
    object_ownership = "BucketOwnerEnforced"
  }
}

resource "aws_s3_bucket_public_access_block" "state" {
  bucket = aws_s3_bucket.state.id

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

resource "aws_s3_bucket_versioning" "state" {
  bucket = aws_s3_bucket.state.id

  # Versioning is how a corrupted or deleted state file is recovered.
  versioning_configuration {
    status = "Enabled"
  }
}
```

- `aws_s3_bucket.state`: the bucket itself. Encryption, versioning and the rest are separate resources, which is the provider's current layout.
- `bucket = local.state_bucket_name`: the globally unique name built above.
- `lifecycle { prevent_destroy = true }`: Terraform refuses any plan that would destroy the bucket. Destroying it would destroy the record of everything Terraform manages. Removing the bucket requires editing the code first.
- `aws_s3_bucket_ownership_controls.state`: sets how object ownership works on the bucket.
  - `object_ownership = "BucketOwnerEnforced"`: disables ACLs. Only IAM and the bucket policy grant access, and the bucket owner owns every object.
- `aws_s3_bucket_public_access_block.state`: four switches that stop public access to the bucket.
  - `block_public_acls`, `ignore_public_acls`: reject new public ACLs and ignore any existing ones.
  - `block_public_policy`, `restrict_public_buckets`: reject public bucket policies and limit access under any such policy to AWS principals in the account.
- `aws_s3_bucket_versioning.state`: turns versioning on.
  - `versioning_configuration { status = "Enabled" }`: each write keeps the previous version, so a corrupted or deleted state file can be restored.

**Encryption and lifecycle — `aws_s3_bucket_server_side_encryption_configuration.state`**

```hcl bootstrap/main.tf
resource "aws_s3_bucket_server_side_encryption_configuration" "state" {
  bucket = aws_s3_bucket.state.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm     = "aws:kms"
      kms_master_key_id = aws_kms_key.state.arn
    }

    # Cuts KMS request volume (and cost) from state reads and lock-file writes.
    bucket_key_enabled = true
  }
}

resource "aws_s3_bucket_lifecycle_configuration" "state" {
  bucket = aws_s3_bucket.state.id

  # Versioning must be on before noncurrent-version rules are accepted.
  depends_on = [aws_s3_bucket_versioning.state]

  rule {
    id     = "expire-old-state-versions"
    status = "Enabled"

    filter {}

    # 90 days of history covers the usual detection window for a bad apply,
    # while keeping the newest 20 versions regardless of age for quiet stacks.
    noncurrent_version_expiration {
      noncurrent_days           = 90
      newer_noncurrent_versions = 20
    }

    # Interrupted multipart uploads are invisible, billable leftovers.
    abort_incomplete_multipart_upload {
      days_after_initiation = 7
    }
  }
}
```

- `aws_s3_bucket_server_side_encryption_configuration.state`: sets the default encryption for every object written to the bucket.
  - `sse_algorithm = "aws:kms"`: encrypt with KMS rather than S3-managed keys, so reading state needs `kms:Decrypt` as well as S3 access.
  - `kms_master_key_id = aws_kms_key.state.arn`: use the key created above. Its ARN is used instead of the alias because the alias can be repointed.
  - `bucket_key_enabled = true`: S3 derives per-object keys from one bucket-level key, so far fewer calls reach KMS. This lowers cost on state reads and lock-file writes.
- `aws_s3_bucket_lifecycle_configuration.state`: expires old data so versioning does not grow without bound.
- `depends_on = [aws_s3_bucket_versioning.state]`: noncurrent-version rules are only accepted once versioning is on, and Terraform sees no reference between the two resources.
- `rule { id = "expire-old-state-versions", status = "Enabled" }`: one named rule, active.
- `filter {}`: an empty filter applies the rule to every object in the bucket.
- `noncurrent_version_expiration`: applies only to superseded versions, never to the current state.
  - `noncurrent_days = 90`: a replaced version is deleted 90 days after it was replaced. That covers the usual time to notice a bad apply.
  - `newer_noncurrent_versions = 20`: the 20 newest noncurrent versions are kept regardless of age. Rarely applied stacks keep history even when nothing was written for months.
- `abort_incomplete_multipart_upload { days_after_initiation = 7 }`: interrupted multipart uploads leave invisible parts that are billed. They are cleaned up after seven days.

**Transport policy — `aws_s3_bucket_policy.state`**

```hcl bootstrap/main.tf
data "aws_iam_policy_document" "state_bucket" {
  statement {
    sid       = "DenyInsecureTransport"
    effect    = "Deny"
    actions   = ["s3:*"]
    resources = [aws_s3_bucket.state.arn, "${aws_s3_bucket.state.arn}/*"]

    principals {
      type        = "*"
      identifiers = ["*"]
    }

    condition {
      test     = "Bool"
      variable = "aws:SecureTransport"
      values   = ["false"]
    }
  }

  statement {
    sid       = "DenyOldTls"
    effect    = "Deny"
    actions   = ["s3:*"]
    resources = [aws_s3_bucket.state.arn, "${aws_s3_bucket.state.arn}/*"]

    principals {
      type        = "*"
      identifiers = ["*"]
    }

    # Mirrors the TLS 1.2 minimum used elsewhere in this stack.
    condition {
      test     = "NumericLessThan"
      variable = "s3:TlsVersion"
      values   = ["1.2"]
    }
  }
}

resource "aws_s3_bucket_policy" "state" {
  bucket = aws_s3_bucket.state.id
  policy = data.aws_iam_policy_document.state_bucket.json

  # Avoids a concurrent-modification error between the policy and the public access block.
  depends_on = [aws_s3_bucket_public_access_block.state]
}
```

- `data "aws_iam_policy_document" "state_bucket"`: two deny statements. An explicit deny overrides any allow, so they hold regardless of IAM policies.
- `sid = "DenyInsecureTransport"`: denies plain HTTP.
  - `effect = "Deny"`, `actions = ["s3:*"]`: every S3 action is covered.
  - `resources = [bucket arn, "bucket arn/*"]`: the bucket ARN covers bucket-level actions and `/*` covers object-level actions. Both are required.
  - `principals { type = "*", identifiers = ["*"] }`: applies to everyone. A deny on everyone cannot lock out a legitimate user who uses TLS.
  - `condition { test = "Bool", variable = "aws:SecureTransport", values = ["false"] }`: matches requests made without TLS.
- `sid = "DenyOldTls"`: denies old protocol versions.
  - `condition { test = "NumericLessThan", variable = "s3:TlsVersion", values = ["1.2"] }`: matches connections negotiated below TLS 1.2. It mirrors the TLS 1.2 minimum used elsewhere in the stack.
- `aws_s3_bucket_policy.state`: attaches the document to the bucket.
- `depends_on = [aws_s3_bucket_public_access_block.state]`: S3 can reject concurrent changes to the policy and the public access block. The dependency serializes them and avoids a concurrent-modification error.

#### iam.tf

**Role names and ARN patterns**

```hcl bootstrap/iam.tf
locals {
  oidc_host = "token.actions.githubusercontent.com"

  # Role names are fixed so that the environment stack and CI can refer to them.
  deploy_role_name = "${var.name}-github-deploy"
  plan_role_name   = "${var.name}-github-terraform-plan"
  apply_role_name  = "${var.name}-github-terraform-apply"

  # Fixed physical names of resources the environment creates later.
  # Bootstrap runs first, so IAM is scoped by name, not by ARN output.
  ecr_repository_arn      = "arn:${local.partition}:ecr:${local.region}:${local.account_id}:repository/${var.name}-*"
  task_definition_arn     = "arn:${local.partition}:ecs:${local.region}:${local.account_id}:task-definition/${var.name}-*:*"
  ecs_service_arn         = "arn:${local.partition}:ecs:${local.region}:${local.account_id}:service/${var.name}-cluster/${var.name}-*"
  task_execution_role_arn = "arn:${local.partition}:iam::${local.account_id}:role/${var.name}-task-execution"
  task_role_arn           = "arn:${local.partition}:iam::${local.account_id}:role/${var.name}-task"
  site_bucket_arn         = "arn:${local.partition}:s3:::${var.name}-site-${local.account_id}"
  cloudfront_dist_arn     = "arn:${local.partition}:cloudfront::${local.account_id}:distribution/*"
  deploy_parameters_arn   = "arn:${local.partition}:ssm:${local.region}:${local.account_id}:parameter/${var.name}/deploy/*"
}
```

- `oidc_host`: the GitHub token issuer host. It prefixes the `aud` and `sub` condition keys in the trust policies and builds the provider URL.
- `deploy_role_name`, `plan_role_name`, `apply_role_name`: fixed role names derived from `var.name`. The environment stack and CI refer to the roles by these names, so they must not change.
- `ecr_repository_arn`: pattern `repository/${var.name}-*` for the application repository. A wildcard on the name prefix limits the deploy role to this environment's repositories.
- `task_definition_arn`: pattern for any revision (`:*`) of a task definition family with the environment prefix.
- `ecs_service_arn`: services inside `${var.name}-cluster` with the environment prefix. ECS service ARNs include the cluster name.
- `task_execution_role_arn`, `task_role_arn`: the two exact roles the ECS tasks use, named in the service module.
- `site_bucket_arn`: the exact site bucket name created by the edge module, with the account ID suffix.
- `cloudfront_dist_arn`: any distribution in the account. CloudFront ARNs have no region, and distribution IDs are random.
- `deploy_parameters_arn`: parameters under `/${var.name}/deploy/`, where the deploy freeze flag lives.
- The comment explains why these are strings: bootstrap runs before the environment exists, so there are no resource outputs to reference, and the names are the contract.

**GitHub OIDC provider — `aws_iam_openid_connect_provider.github`**

```hcl bootstrap/iam.tf
resource "aws_iam_openid_connect_provider" "github" {
  url            = "https://${local.oidc_host}"
  client_id_list = ["sts.amazonaws.com"]

  # thumbprint_list is omitted on purpose: for GitHub, AWS validates the certificate
  # against its own trusted CA library and ignores any thumbprint.
}
```

- `url = "https://${local.oidc_host}"`: GitHub's token issuer. AWS fetches its signing keys from here to verify tokens. An account can hold one provider per URL.
- `client_id_list = ["sts.amazonaws.com"]`: the audience GitHub Actions requests when it calls AWS. A token with another audience is rejected.
- `thumbprint_list` is omitted: for GitHub, AWS validates the certificate against its own trusted CA library and ignores any thumbprint.

**Trust policies — `trust_environment`, `trust_pull_request`**

```hcl bootstrap/iam.tf
data "aws_iam_policy_document" "trust_environment" {
  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRoleWithWebIdentity"]

    principals {
      type        = "Federated"
      identifiers = [aws_iam_openid_connect_provider.github.arn]
    }

    condition {
      test     = "StringEquals"
      variable = "${local.oidc_host}:aud"
      values   = ["sts.amazonaws.com"]
    }

    # Exact match (StringEquals, no wildcard): only jobs that run in the protected
    # GitHub Environment, and so passed its required-reviewer gate, get these roles.
    condition {
      test     = "StringEquals"
      variable = "${local.oidc_host}:sub"
      values   = ["repo:${var.github_repository}:environment:${var.github_environment}"]
    }
  }
}

data "aws_iam_policy_document" "trust_pull_request" {
  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRoleWithWebIdentity"]

    principals {
      type        = "Federated"
      identifiers = [aws_iam_openid_connect_provider.github.arn]
    }

    condition {
      test     = "StringEquals"
      variable = "${local.oidc_host}:aud"
      values   = ["sts.amazonaws.com"]
    }

    # Subject GitHub issues to jobs triggered by pull_request events; it carries no environment.
    condition {
      test     = "StringEquals"
      variable = "${local.oidc_host}:sub"
      values   = ["repo:${var.github_repository}:pull_request"]
    }
  }
}
```

- `trust_environment`: who may assume the deploy and apply roles.
  - `actions = ["sts:AssumeRoleWithWebIdentity"]`: the call GitHub Actions makes to exchange its OIDC token for credentials. No access keys are stored anywhere.
  - `principals { type = "Federated" ... }`: the principal is the OIDC provider, not an account or user.
  - `condition ... "${local.oidc_host}:aud"`: requires the token audience to be `sts.amazonaws.com`.
  - `condition ... "${local.oidc_host}:sub"`: requires the subject `repo:<owner/repo>:environment:<name>`. `StringEquals` is an exact match with no wildcard, so only jobs in this repository running in the protected GitHub Environment qualify. Those jobs have passed the environment's required-reviewer gate.
- `trust_pull_request`: who may assume the plan role.
  - Same effect, action, principal and `aud` condition as above.
  - `condition ... "${local.oidc_host}:sub"`: requires the subject `repo:<owner/repo>:pull_request`, which GitHub issues to jobs triggered by `pull_request` events. That subject carries no environment, so it never matches the environment trust policy and cannot reach the deploy or apply roles.

**Deploy role — `aws_iam_role.deploy`**

```hcl bootstrap/iam.tf
resource "aws_iam_role" "deploy" {
  name               = local.deploy_role_name
  description        = "GitHub Actions application deploys for ${var.name}"
  assume_role_policy = data.aws_iam_policy_document.trust_environment.json

  # One hour: a deploy (build push, service update, site sync) finishes well inside it,
  # and a leaked token stops working soon after.
  max_session_duration = 3600
}

data "aws_iam_policy_document" "deploy" {
  statement {
    sid       = "EcrAuthToken"
    effect    = "Allow"
    actions   = ["ecr:GetAuthorizationToken"]
    resources = ["*"] # AWS: this action does not support resource-level permissions.
  }

  statement {
    sid    = "EcrPush"
    effect = "Allow"
    actions = [
      "ecr:BatchCheckLayerAvailability",
      "ecr:BatchGetImage",
      "ecr:CompleteLayerUpload",
      "ecr:DescribeImages",
      "ecr:GetDownloadUrlForLayer",
      "ecr:InitiateLayerUpload",
      "ecr:PutImage",
      "ecr:UploadLayerPart",
    ]
    resources = [local.ecr_repository_arn]
  }

  statement {
    sid       = "EcsRegisterTaskDefinition"
    effect    = "Allow"
    actions   = ["ecs:RegisterTaskDefinition"]
    resources = [local.task_definition_arn]
  }

  # register-task-definition --tags (the release SHA on each revision) is a tag-on-create
  # request; ECS authorizes it as ecs:TagResource. The condition allows tags only at
  # registration, so the role cannot retag existing resources.
  statement {
    sid       = "EcsTagTaskDefinitionOnRegister"
    effect    = "Allow"
    actions   = ["ecs:TagResource"]
    resources = [local.task_definition_arn]

    condition {
      test     = "StringEquals"
      variable = "ecs:CreateAction"
      values   = ["RegisterTaskDefinition"]
    }
  }

  # Deploy freeze flag (scripts/ci/freeze.sh): rollback sets it, deploys read it, unfreeze
  # deletes it. Scoped to parameters under /<name>/deploy/.
  statement {
    sid       = "DeployFreezeParameter"
    effect    = "Allow"
    actions   = ["ssm:DeleteParameter", "ssm:GetParameter", "ssm:PutParameter"]
    resources = [local.deploy_parameters_arn]
  }

  statement {
    sid       = "EcsDescribeTaskDefinition"
    effect    = "Allow"
    actions   = ["ecs:DescribeTaskDefinition"]
    resources = ["*"] # AWS: this action does not support resource-level permissions.
  }

  statement {
    sid       = "EcsUpdateService"
    effect    = "Allow"
    actions   = ["ecs:DescribeServices", "ecs:UpdateService"]
    resources = [local.ecs_service_arn]
  }

  # Registering a task definition and updating the service hand the task roles to ECS;
  # naming exactly these two roles means a deploy cannot attach any other role.
  statement {
    sid       = "PassTaskRoles"
    effect    = "Allow"
    actions   = ["iam:PassRole"]
    resources = [local.task_execution_role_arn, local.task_role_arn]

    condition {
      test     = "StringEquals"
      variable = "iam:PassedToService"
      values   = ["ecs-tasks.amazonaws.com"]
    }
  }

  statement {
    sid       = "SiteBucketList"
    effect    = "Allow"
    actions   = ["s3:ListBucket"]
    resources = [local.site_bucket_arn]
  }

  statement {
    sid       = "SiteBucketObjects"
    effect    = "Allow"
    actions   = ["s3:DeleteObject", "s3:GetObject", "s3:PutObject"]
    resources = ["${local.site_bucket_arn}/*"]
  }

  # The site bucket uses SSE-KMS; uploads need the key. The alias condition limits
  # use to the key the edge module tags as alias/<name>-site.
  statement {
    sid       = "SiteBucketKey"
    effect    = "Allow"
    actions   = ["kms:Decrypt", "kms:Encrypt", "kms:GenerateDataKey"]
    resources = ["arn:${local.partition}:kms:${local.region}:${local.account_id}:key/*"]

    condition {
      test     = "ForAnyValue:StringEquals"
      variable = "kms:ResourceAliases"
      values   = ["alias/${var.name}-site"]
    }
  }

  # Distribution IDs are random and unknown before the edge module runs, so this is
  # scoped to distributions in this account (CloudFront has no region in its ARNs).
  statement {
    sid       = "CloudFrontInvalidate"
    effect    = "Allow"
    actions   = ["cloudfront:CreateInvalidation", "cloudfront:GetInvalidation"]
    resources = [local.cloudfront_dist_arn]
  }
}

resource "aws_iam_role_policy" "deploy" {
  name   = "deploy"
  role   = aws_iam_role.deploy.id
  policy = data.aws_iam_policy_document.deploy.json
}
```

- `aws_iam_role.deploy`: the role application release jobs assume.
  - `name`, `description`: the fixed name from the locals and a description naming its purpose.
  - `assume_role_policy = ...trust_environment.json`: only jobs in the protected GitHub Environment can assume it.
  - `max_session_duration = 3600`: one hour, the shortest allowed. A deploy (image push, service update, site sync) finishes well inside it, and a leaked token expires soon.
- `data "aws_iam_policy_document" "deploy"`: permissions, one statement per task.
  - `EcrAuthToken`: `ecr:GetAuthorizationToken` for `docker login`. AWS does not support resource-level permissions on this action, so `resources = ["*"]`.
  - `EcrPush`: the layer upload and image read/write actions needed to push a tag, limited to `local.ecr_repository_arn`.
  - `EcsRegisterTaskDefinition`: registers a new revision, limited to task definitions with this environment's prefix.
  - `EcsTagTaskDefinitionOnRegister`: `ecs:TagResource` on task definitions, so `register-task-definition --tags` can put the release SHA on each revision. The condition `ecs:CreateAction = RegisterTaskDefinition` allows tags only at registration, so the role cannot retag existing resources.
  - `DeployFreezeParameter`: get, put and delete on SSM parameters under `/${var.name}/deploy/*` (`local.deploy_parameters_arn`). `scripts/ci/freeze.sh` uses them for the deploy freeze flag: rollback sets it, deploys read it, unfreeze deletes it.
  - `EcsDescribeTaskDefinition`: reads the current definition to copy it. No resource-level permissions, so `*`.
  - `EcsUpdateService`: `ecs:DescribeServices` and `ecs:UpdateService` on this environment's services only, to roll out the new revision and wait for it.
  - `PassTaskRoles`: `iam:PassRole` on exactly the task execution role and the task role. Registering a task definition and updating the service hand these roles to ECS, so naming them means a deploy cannot attach any other role.
    - `iam:PassedToService = ecs-tasks.amazonaws.com`: the roles can be passed only to ECS tasks, not to another service.
  - `SiteBucketList`: `s3:ListBucket` on the bucket itself, needed by sync to compare keys.
  - `SiteBucketObjects`: get, put and delete on objects under the bucket (`/*`), so a sync can upload and remove files.
  - `SiteBucketKey`: the site bucket uses SSE-KMS, so uploads need the key.
    - `resources = [".../key/*"]`: key IDs are not known to bootstrap.
    - `ForAnyValue:StringEquals` on `kms:ResourceAliases` with `alias/${var.name}-site`: limits use to the key carrying that alias, which the edge module creates.
  - `CloudFrontInvalidate`: create and read invalidations on distributions in this account. IDs are random and unknown before the edge module runs.
- `aws_iam_role_policy.deploy`: attaches the document inline to the role. Inline policies are deleted with the role and cannot be attached elsewhere.

**Plan role — `aws_iam_role.terraform_plan`**

```hcl bootstrap/iam.tf
resource "aws_iam_role" "terraform_plan" {
  name               = local.plan_role_name
  description        = "Read-only GitHub Actions role that runs terraform plan on pull requests for ${var.name}"
  assume_role_policy = data.aws_iam_policy_document.trust_pull_request.json

  # One hour: a plan of this stack takes minutes; pull-request tokens should be short-lived.
  max_session_duration = 3600
}

resource "aws_iam_role_policy_attachment" "terraform_plan_read_only" {
  role = aws_iam_role.terraform_plan.name
  # ReadOnlyAccess does not allow secretsmanager:GetSecretValue (only Describe/List/GetResourcePolicy)
  # and has no kms:Decrypt, so secret values stay unreadable.
  policy_arn = "arn:${local.partition}:iam::aws:policy/ReadOnlyAccess"
}

data "aws_iam_policy_document" "terraform_plan" {
  statement {
    sid       = "StateBucketList"
    effect    = "Allow"
    actions   = ["s3:ListBucket"]
    resources = [aws_s3_bucket.state.arn]
  }

  statement {
    sid       = "StateRead"
    effect    = "Allow"
    actions   = ["s3:GetObject"]
    resources = ["${aws_s3_bucket.state.arn}/*"]
  }

  # use_lockfile makes plan create and delete <key>.tflock (S3 backend docs), so write is
  # allowed on lock files only. State objects stay read-only for this role.
  statement {
    sid       = "StateLockFile"
    effect    = "Allow"
    actions   = ["s3:DeleteObject", "s3:GetObject", "s3:PutObject"]
    resources = ["${aws_s3_bucket.state.arn}/*.tflock"]
  }

  statement {
    sid       = "StateKey"
    effect    = "Allow"
    actions   = ["kms:Decrypt", "kms:DescribeKey", "kms:GenerateDataKey"]
    resources = [aws_kms_key.state.arn]
  }
}

resource "aws_iam_role_policy" "terraform_plan" {
  name   = "state-access"
  role   = aws_iam_role.terraform_plan.id
  policy = data.aws_iam_policy_document.terraform_plan.json
}
```

- `aws_iam_role.terraform_plan`: the role pull-request jobs assume to run `terraform plan`.
  - `assume_role_policy = ...trust_pull_request.json`: assumable from `pull_request` events, which carry no environment and no approval.
  - `max_session_duration = 3600`: a plan takes minutes, and pull-request tokens should be short-lived.
- `aws_iam_role_policy_attachment.terraform_plan_read_only`: attaches the AWS-managed `ReadOnlyAccess` so plan can refresh every resource type.
  - `policy_arn`: built with `local.partition`. `ReadOnlyAccess` does not allow `secretsmanager:GetSecretValue` and has no `kms:Decrypt`, so secret values stay unreadable.
- `data "aws_iam_policy_document" "terraform_plan"`: the state access that read-only does not cover.
  - `StateBucketList`: list the state bucket.
  - `StateRead`: read objects, so plan can load state.
  - `StateLockFile`: the S3 backend with `use_lockfile` creates and deletes `<key>.tflock` during plan. Write is therefore allowed on `*.tflock` objects only, and state objects stay read-only.
  - `StateKey`: decrypt, describe and generate data keys on the state key only. `GenerateDataKey` is needed to write the encrypted lock file.
- `aws_iam_role_policy.terraform_plan`: attaches the document inline, named `state-access`.

**Apply role — `aws_iam_role.terraform_apply`**

```hcl bootstrap/iam.tf
resource "aws_iam_role" "terraform_apply" {
  name               = local.apply_role_name
  description        = "GitHub Actions role that runs terraform apply for ${var.name} after approval"
  assume_role_policy = data.aws_iam_policy_document.trust_environment.json

  # Two hours: creating Aurora, CloudFront and ACM validation can outlast one hour,
  # and credentials from web identity cannot be refreshed mid-run.
  max_session_duration = 7200
}

resource "aws_iam_role_policy_attachment" "terraform_apply_admin" {
  role = aws_iam_role.terraform_apply.name
  # AdministratorAccess is deliberate: Terraform creates IAM roles, KMS keys, networking and
  # CloudFront, so a narrower policy would be incomplete or equal to admin in practice.
  # The control is the trust policy: only jobs in the protected GitHub Environment
  # (required reviewers) can assume this role.
  policy_arn = "arn:${local.partition}:iam::aws:policy/AdministratorAccess"
}
```

- `aws_iam_role.terraform_apply`: the role that runs `terraform apply` after approval.
  - `assume_role_policy = ...trust_environment.json`: only jobs in the protected GitHub Environment, which requires reviewers, can assume it.
  - `max_session_duration = 7200`: two hours. Creating Aurora, CloudFront and ACM validation can outlast one hour, and credentials from web identity cannot be refreshed mid-run.
- `aws_iam_role_policy_attachment.terraform_apply_admin`: attaches `AdministratorAccess`.
  - `policy_arn`: deliberate. Terraform creates IAM roles, KMS keys, networking and CloudFront, so a narrower policy would be incomplete or equal to admin in practice. The control is the trust policy, not the permissions.

#### variables.tf

**Validated variables**

```hcl bootstrap/variables.tf
variable "name" {
  type        = string
  description = "Environment name used as the prefix for every resource, for example patent-prod. Must match the name the environment stack passes to its modules."

  validation {
    condition     = can(regex("^[a-z][a-z0-9-]{1,30}[a-z0-9]$", var.name))
    error_message = "name must be 3-32 characters of lowercase letters, digits and hyphens, starting with a letter and not ending with a hyphen."
  }
}

variable "tags" {
  type        = map(string)
  description = "Tags applied to every resource through the provider default_tags."
  default     = {}
}

variable "aws_region" {
  type        = string
  description = "Region of the state bucket, its KMS key and the application environment."
}

variable "github_repository" {
  type        = string
  description = "GitHub repository allowed to assume the roles, in owner/repo form."

  validation {
    condition     = can(regex("^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$", var.github_repository))
    error_message = "github_repository must be in owner/repo form and contain only letters, digits, underscore, dot and hyphen."
  }
}

variable "github_environment" {
  type        = string
  description = "Name of the GitHub Environment (with required reviewers) that may deploy to this account. It is the only environment the deploy and apply roles trust."

  validation {
    condition     = length(var.github_environment) > 0 && !can(regex("[*?]", var.github_environment))
    error_message = "github_environment must be a non-empty exact name with no wildcard characters."
  }
}
```

- `name`: the prefix on every resource, and it must equal the name the environment stack passes to its modules, or the name-scoped IAM would not match.
  - `regex("^[a-z][a-z0-9-]{1,30}[a-z0-9]$", ...)`: 3 to 32 characters, lowercase letters, digits and hyphens, starting with a letter and not ending in a hyphen. This keeps derived names, such as the bucket name, within AWS limits.
  - `can(...)`: turns a non-match into `false` so the `error_message` is shown instead of a raw regex error.
- `tags`: applied to every resource through the provider `default_tags`. It defaults to an empty map.
- `aws_region`: the region of the state bucket, its KMS key and the application environment.
- `github_repository`: the repository allowed to assume the roles.
  - `regex("^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$", ...)`: requires `owner/repo` with only characters GitHub allows. It rejects wildcards, so the `sub` condition cannot be widened by input.
- `github_environment`: the one environment the deploy and apply roles trust.
  - `length(var.github_environment) > 0`: an empty name would build a subject that matches no real job.
  - `!can(regex("[*?]", ...))`: rejects wildcard characters, so the trust condition stays an exact match.

#### outputs.tf

**Backend settings — `backend_config`**

```hcl bootstrap/outputs.tf
output "backend_config" {
  description = "Backend settings for the environment stacks (add key per stack). Locking uses S3 lock files, not DynamoDB."
  value = {
    bucket       = aws_s3_bucket.state.id
    region       = local.region
    encrypt      = true
    kms_key_id   = aws_kms_key.state.arn
    use_lockfile = true
  }
}
```

- `value = { ... }`: one object holding the settings an `s3` backend block needs. It is computed from the resources, so the environment stacks cannot drift from what bootstrap created.
  - `bucket = aws_s3_bucket.state.id`: the state bucket name.
  - `region = local.region`: the bucket's region.
  - `encrypt = true`: the backend requests server-side encryption for state objects.
  - `kms_key_id = aws_kms_key.state.arn`: the state key, so new objects use it.
  - `use_lockfile = true`: locking through S3 lock files (`<key>.tflock`). No DynamoDB table is created. This is why the plan role can write `*.tflock`.
- Each environment adds its own `key`, which this output leaves out.

## GitHub

A root stack for the repository settings that the pipeline depends on, applied by a person with admin rights on the repository. CI does not run it, because the workflow `GITHUB_TOKEN` cannot change repository settings. See [Environments](/environments) for how it is used.

- **Environments:** `dev`, `staging` and `prod`, each with reviewers, deployment limited to `main`, and the variables the workflows read.
- **Repository variables:** the settings for pull-request plan jobs, which name no Environment and so cannot read Environment variables.
- **Ruleset on `main`:** pull request review, no deletion, no force push, and `ci-ok` as the one required check.

| Inputs | Outputs |
|---|---|
| `github_owner`, `repository`, `project`, `aws_region`, `environments`, `required_approving_review_count` | none |

`environments` takes one object for each of `dev`, `staging` and `prod`. It carries the reviewers, the `bootstrap` outputs and the `envs/<name>` outputs. Validation requires exactly those three keys, at least one reviewer on `prod`, and an `https://` public URL with no path.

### Walkthrough

#### main.tf

**Environments and branch policy — `github_repository_environment.this`**

```hcl github/main.tf
resource "github_repository_environment" "this" {
  for_each = var.environments

  repository          = var.repository
  environment         = each.key
  prevent_self_review = each.value.prevent_self_review
  # Admins wait for reviewers like everyone else. On GitHub Free, Pro and Team this setting,
  # like required reviewers, works only in public repositories.
  can_admins_bypass = false

  dynamic "reviewers" {
    for_each = length(each.value.reviewer_users) + length(each.value.reviewer_teams) > 0 ? [1] : []
    content {
      users = [for u in each.value.reviewer_users : tonumber(data.github_user.reviewer[u].id)]
      teams = [for t in each.value.reviewer_teams : tonumber(data.github_team.reviewer[t].id)]
    }
  }

  # Only main may deploy. Without this, a workflow on any branch could name the Environment
  # and receive its OIDC subject, and with it the deploy and apply roles.
  deployment_branch_policy {
    protected_branches     = false
    custom_branch_policies = true
  }
}

resource "github_repository_environment_deployment_policy" "main" {
  for_each = github_repository_environment.this

  repository     = var.repository
  environment    = each.value.environment
  branch_pattern = "main"
}
```

- `for_each = var.environments`: one GitHub Environment for each key. The key must equal `github_environment` in that account's bootstrap, because the OIDC trust matches the name exactly.
- `can_admins_bypass = false`: administrators wait for reviewers like everyone else.
- `dynamic "reviewers"`: sets reviewers only when the environment lists some. The provider takes numeric IDs, so the blocks look the IDs up from logins and team slugs.
- `deployment_branch_policy` with `custom_branch_policies = true`: turns on a branch allow list instead of the protected-branch rule.
- `github_repository_environment_deployment_policy.main`: the allow list holds one entry, `main`. A workflow on any other branch cannot name the Environment, so it cannot receive its OIDC subject or assume the deploy and apply roles.

**Required check — `github_repository_ruleset.main`**

```hcl github/main.tf
resource "github_repository_ruleset" "main" {
  name        = "main"
  repository  = var.repository
  target      = "branch"
  enforcement = "active"

  conditions {
    ref_name {
      include = ["~DEFAULT_BRANCH"]
      exclude = []
    }
  }

  rules {
    deletion         = true
    non_fast_forward = true

    pull_request {
      required_approving_review_count = var.required_approving_review_count
      dismiss_stale_reviews_on_push   = true
    }

    required_status_checks {
      # The branch must be up to date with main, so the commit that CI tested is the commit
      # that deploy.yml builds.
      strict_required_status_checks_policy = true

      # The one required check (ci.yml). integration_id pins it to the GitHub Actions app,
      # so no other app or token can report a passing "ci-ok".
      required_check {
        context        = "ci-ok"
        integration_id = 15368
      }
    }
  }
}
```

- `include = ["~DEFAULT_BRANCH"]`: the rule follows the default branch.
- `deletion = true`, `non_fast_forward = true`: these rules block deleting `main` and force-pushing to it.
- `pull_request`: requires `required_approving_review_count` approvals (default 1), and a new push dismisses earlier approvals.
- `strict_required_status_checks_policy = true`: the branch must be up to date with `main`, so the commit CI tested is the commit `deploy.yml` builds.
- `required_check`: `ci-ok` is the single required check. `integration_id = 15368` pins it to the GitHub Actions app, so no other app or token can report a passing `ci-ok`.

#### variables.tf and providers.tf

- `environments` is a `map(object)` with three validations (exact keys, a reviewer on `prod`, `https://` URLs). Its description says which `terraform output` supplies each value.
- `providers.tf` authenticates with `GITHUB_TOKEN` from the shell. The token needs admin rights on the repository.
- `SLACK_WEBHOOK_URL` is not managed here. It is a credential, and Terraform would store it in state.
