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

调用Terraform获取EC2 AMI时遇403权限错误,求排查方案

Terraform读取EC2 AMI时403权限错误的解决与调试

错误详情

执行Terraform计划时出现以下权限错误:

Plan: 14 to add, 0 to change, 0 to destroy.

Error: reading EC2 AMIs: UnauthorizedOperation: You are not authorized to perform this operation.
    status code: 403, request id: aeb56889-5181-4fd8-bb1f-456784e08bf2

  with data.aws_ami.ami_linux,
  on _environment-local.tf line 37, in data "aws_ami" "ami_linux":
  37: data "aws_ami" "ami_linux" {

Error: Terraform exited with code 1.
Error: Process completed with exit code 1.

对应的AMI查询代码:

data "aws_ami" "ami_linux" {
  most_recent = true
  name_regex  = "^amzn2-ami-hvm-2.*-x86_64-gp2"

  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-2.0.202*"]
  }

  owners = ["amazon"]
}

已配置的IAM资源:

resource "aws_iam_role_policy_attachment" "gha_describe_images" {
  role       = aws_iam_role.gaadmin.name
  policy_arn = aws_iam_policy.gha_describe_images.arn
}

resource "aws_iam_policy" "gha_describe_images" {
  name   = "${var.brand}-${var.name}-describe-images"
  policy = data.aws_iam_policy_document.gha_describe_images.json
}

data "aws_iam_policy_document" "gha_describe_images" {
  statement {
    actions = [
      "ec2:DescribeImages",
    ]
    effect    = "Allow"
    resources = [
      "arn:aws:ec2:us-east-1:1234567890:*"
    ]
  }
}

问题根源

你配置的IAM策略中,resources字段指定了自己账户(1234567890)的EC2资源,但要查询的是Amazon官方的公开AMI,这些AMI属于Amazon的账户而非你的账户。ec2:DescribeImages是全局描述类API,不需要指定具体资源ARN,指定特定账户的资源会导致策略无法匹配对Amazon账户AMI的查询操作,从而触发403错误。

修复方法

修改IAM策略文档,将resources改为*,或者直接移除resources字段(描述类API默认不需要资源限制):

data "aws_iam_policy_document" "gha_describe_images" {
  statement {
    actions = [
      "ec2:DescribeImages",
    ]
    effect    = "Allow"
    resources = ["*"] # 改为全局匹配
  }
}

或更简洁的写法:

data "aws_iam_policy_document" "gha_describe_images" {
  statement {
    actions = [
      "ec2:DescribeImages",
    ]
    effect = "Allow"
  }
}

进一步调试步骤

  • CLI权限验证:使用Terraform所用的IAM角色凭证,执行AWS CLI命令测试权限:

    aws ec2 describe-images --owners amazon --filters "Name=name,Values=amzn2-ami-hvm-2.0.202*"
    

    若返回403则说明权限配置问题;若成功返回结果,检查Terraform是否正确使用了该角色。

  • IAM角色关联检查:确认Terraform执行时使用的是gaadmin角色,而非本地AWS凭证或其他角色。可通过设置AWS_PROFILE环境变量或在Terraform provider中指定role_arn验证。

  • IAM策略生效确认:登录AWS控制台,进入gaadmin角色详情页,检查gha_describe_images策略是否已正确附加,同时查看是否存在权限边界或其他拒绝策略限制了ec2:DescribeImages操作。

  • CloudTrail日志排查:启用AWS CloudTrail,查看对应的DescribeImagesAPI调用日志,确认调用者身份、请求参数、资源ARN等信息,进一步定位权限不匹配的原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:58:11