You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform部署ECR镜像到ECS遇权限错误:无ecr:GetAuthorizationToken权限

问题分析

错误提示明确指出,ECS任务执行角色ecsExecution-1缺少ecr:GetAuthorizationToken权限,同时拉取ECR镜像还需要ecr:BatchGetImage、ecr:GetDownloadUrlForLayer等关联权限,导致任务无法获取ECR授权、拉取镜像。

解决方案

为ECS执行角色添加访问ECR的必要权限即可解决问题,最简单的方式是附着AWS托管的AmazonEC2ContainerRegistryReadOnly策略,也可自定义更精细的权限策略。

修改后的Terraform代码

在现有代码基础上添加角色策略附着逻辑:

resource "aws_ecs_cluster" "first-cluster" {
  name = "test-docker-deploy"
}

resource "aws_ecs_task_definition"  "first-task" {
  family                = "first-task"
  container_definitions = <<TASK_DEFINITION
  [
    {
      "name": "first-task",
      "image": "899696473236.dkr.ecr.us-east-1.amazonaws.com/first-repo:nginx-demo",
      "cpu": 256,
      "memory": 512,
      "essential": true,
      "portMappings": [
        {
          "containerPort": 80,
          "hostPort": 80
        }
      
      ]
    }

  ]
  TASK_DEFINITION
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  cpu                      = 256
  memory                   = 512
  execution_role_arn       = aws_iam_role.Execution_Role.arn

}

resource "aws_iam_role" "Execution_Role" {
  name                = "ecsExecution-1"
  assume_role_policy  = data.aws_iam_policy_document.role_policy.json
}

data "aws_iam_policy_document" "role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

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

# 为执行角色添加ECR只读权限
resource "aws_iam_role_policy_attachment" "ecs_execution_ecr_readonly" {
  role       = aws_iam_role.Execution_Role.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly"
}

resource "aws_ecs_service" "first-service"{
    name                    = "docker-service"
    cluster                 = aws_ecs_cluster.first-cluster.id
    task_definition         = aws_ecs_task_definition.first-task.arn
    launch_type             = "FARGATE"
    desired_count           = 1

    network_configuration {
        subnets            = [aws_default_subnet.subnet-a.id]
        assign_public_ip   = true
    }
}

resource "aws_default_vpc" "default" {
}

resource "aws_default_subnet" "subnet-a" {
  availability_zone = "us-east-1a"
}

关键说明

  • AmazonEC2ContainerRegistryReadOnly托管策略包含了ECR镜像拉取所需的全部权限:ecr:GetAuthorizationToken、ecr:BatchCheckLayerAvailability、ecr:GetDownloadUrlForLayer、ecr:BatchGetImage,完全满足当前场景需求。
  • 若需更精细的权限控制,可自定义IAM策略,仅允许访问指定ECR仓库资源,而非通配符*。

内容的提问来源于stack exchange,提问作者Adnivas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 19:45:55