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

动态生成AWS IAM policy document时principals参数报错如何解决?

报错原因&解决方案

核心报错原因

aws_iam_policy_document资源的statement块中,principals是嵌套块类型,不属于普通键值对参数,不能直接通过principals = lookup(xxx)的方式赋值,必须按照嵌套块的语法声明。

可行修改方案

步骤1:修改模块内的aws_iam_policy_document配置

将原来直接赋值principals的逻辑替换为dynamic动态嵌套块,修改后的代码如下:

data "aws_iam_policy_document" "bucket_policy" {
  dynamic "statement" {
    for_each = var.policies_list
    iterator = role
    content {
      effect = lookup(role.value, "effect", null)
      actions = lookup(role.value, "actions", null)
      resources = lookup(role.value, "resources", null)
      
      # 动态生成principals嵌套块
      dynamic "principals" {
        # 仅当当前statement配置了principals时才生成块
        for_each = lookup(role.value, "principals", null) != null ? [role.value.principals] : []
        content {
          type        = principals.value.type
          identifiers = principals.value.identifiers
        }
      }
    }
  }
}

步骤2:确认变量类型定义(可选,避免后续类型校验报错)

建议在模块的variables.tf中补充policies_list的类型声明,明确principals的字段结构:

variable "policies_list" {
  type = list(object({
    effect     = string
    principals = optional(object({
      type        = string
      identifiers = list(string)
    }))
    actions   = list(string)
    resources = list(string)
  }))
  description = "S3 bucket IAM policy statement list"
  default = []
}

步骤3:验证配置

你原有模块调用的代码无需调整,直接执行terraform plan校验,不会再出现principals参数不支持的报错。如果部分策略不需要配置principals,直接在policies_list的对应项中省略principals字段即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:36:01