如何为 AWS Batch 作业设置适当的 IAM 角色?

How to set proper IAM role(s) for an AWS Batch job?

我的作业在提交到 Batch 服务后,从 RUNNABLE 状态变为 FAILED 状态,并显示以下作业状态错误消息(来自 AWS 控制台):

ECS was unable to assume the role 'arn:aws:iam::347134692569:role/my-custom-role' that was provided for this task. Please verify that the role being passed has the proper trust relationship and permissions and that your IAM user has permissions to pass this role.

上面提到的角色是使用 Terraform 管理的,有两个策略附件(AWSBatchServiceRoleAmazonEC2ContainerServiceforEC2Role),如下所示:

resource "aws_iam_role" "batch" {
  name               = "my-custom-role"
  assume_role_policy = <<EOF
{
    "Version": "2012-10-17",
    "Statement":
    [
      {
          "Action": "sts:AssumeRole",
          "Effect": "Allow",
          "Principal": {
            "Service": "batch.amazonaws.com"
          }
      },
      {
          "Action": "sts:AssumeRole",
          "Effect": "Allow",
          "Principal": {
            "Service": "ec2.amazonaws.com"
          }
      },
      {
          "Action": "sts:AssumeRole",
          "Effect": "Allow",
          "Principal": {
            "Service": "ecs.amazonaws.com"
          }
      }
    ]
}
EOF
  tags = {
    Terraform = "true"
  }
}

# attach a policy to the role that allows using AWS Batch service
resource "aws_iam_role_policy_attachment" "batch_service_role" {
  role       = data.aws_iam_role.batch.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSBatchServiceRole"
}

# attach a policy to the role that allows using AWS Elastic Container service
resource "aws_iam_role_policy_attachment" "elastic_container_service_role" {
  role       = aws_iam_role.batch.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role"
}

以上角色用作计算环境的服务角色以及作业定义的作业角色。

上面的内容似乎没有提供足够的权限来启用承担角色 and/or 必要的信任关系。我还能尝试什么来克服这个错误?

根据评论,通过添加 ecs-tasks.amazonaws.com 作为 AssumeRole 的原则解决了问题。

似乎需要与 ECS 任务执行角色和任务相同的权限: