Code Snip: This sites ECR Terraform

Saturday, Jan 10, 2026

Code Snip: The Terraform configuration the ECR repositories

Part of the Terraform for this site This Website

resource "aws_ecr_repository" "site_containers" {
  for_each = var.backend_tasks

  name = "${each.key}_container"
  image_tag_mutability = "IMMUTABLE_WITH_EXCLUSION"

  image_tag_mutability_exclusion_filter {
    filter = "latest*"
    filter_type = "WILDCARD"
  }

  encryption_configuration {
    encryption_type = "KMS"
  }

  force_delete = true

  image_scanning_configuration {
    scan_on_push = true
  }

}

data "aws_iam_policy_document" "container_access" {
  statement {
    sid = "server_container_access"
    effect = "Allow"
    principals {
      identifiers = [aws_iam_role.ecs_task_execution_role.arn]
      type = "AWS"
    }
    actions = [
      "ecr:BatchCheckLayerAvailability",
      "ecr:BatchGetImage",
      "ecr:DescribeImages",
      "ecr:DescribeRepositories",
      "ecr:GetAuthorizationToken",
      "ecr:GetDownloadUrlForLayer",
      "ecr:ListImages"
    ]
  }
}

resource "aws_ecr_repository_policy" "server_access_policy_attach" {
  for_each = var.backend_tasks

  policy     = data.aws_iam_policy_document.container_access.json
  repository = "${each.key}_container"
}

resource "aws_ecr_lifecycle_policy" "container_lifecycle" {
  for_each = var.backend_tasks

  repository = "${each.key}_container"
  policy = <<EOF
{
  "rules": [
    {
      "rulePriority": 1,
      "description": "Clean up old versions of the current version of the app.",
      "selection": {
        "tagStatus": "tagged",
        "tagPrefixList": ["latest"],
        "countType": "imageCountMoreThan",
        "countNumber": 10
      },
      "action": {
        "type": "expire"
      }
    },
    {
      "rulePriority": 2,
      "description": "Clean up all old versions",
      "selection": {
        "tagStatus": "any",
        "countType": "imageCountMoreThan",
        "countNumber": 5
      },
      "action": {
        "type": "expire"
      }
    }
  ]
}
EOF
}