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

Terraform中如何正确引用for_each创建的aws_iam_policy_document数据源

修正Terraform中IAM角色与策略文档的匹配问题

你的代码问题出在策略文档的引用路径错误,只需调整assume_role_policy的插值语法即可:

修正后的完整代码

# Policy to allow services to assume the role
data "aws_iam_policy_document" "this" {
  for_each           = var.lambda_configuration
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "Service"

      identifiers = [
        "lambda.amazonaws.com",
        "apigateway.amazonaws.com",
      ]
    }
  }
}

# IAM role for executing the Lambda function
resource "aws_iam_role" "this" {
  for_each           = var.lambda_configuration
  name               = "my_lambda_${each.key}_Executor_Role"
  description        = "Role for executing my_lambda-${each.key} function"
  assume_role_policy = data.aws_iam_policy_document.this[each.key].json
}

关键修正说明

  • 当使用for_each创建数据源实例后,必须通过数据源名称[each.key]的语法访问对应实例。你的数据源名称是this,因此正确引用路径为data.aws_iam_policy_document.this[each.key].json
  • 原代码错误地使用了不存在的数据源名称assume_role_policy_,同时未正确使用索引语法定位for_each生成的实例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:01:37