【问题标题】:Terraform AWS IAM Iterate Over Rendered JSON PoliciesTerraform AWS IAM 迭代呈现的 JSON 策略
【发布时间】:2021-06-04 12:58:00
【问题描述】:

如何在 aws_iam_policy 中迭代 JSON 呈现的 data.aws_iam_policy_document 文档?

data "aws_iam_policy_document" "role_1" {

  statement {
    sid = "CloudFront1"

    actions = [
      "cloudfront:ListDistributions",
      "cloudfront:ListStreamingDistributions"
    ]
    resources = ["*"]
  }
}

data "aws_iam_policy_document" "role_2" {
  statement {
    sid = "CloudFront2"

    actions = [
      "cloudfront:CreateInvalidation",
      "cloudfront:GetDistribution",
      "cloudfront:GetInvalidation",
      "cloudfront:ListInvalidations"
    ]
    resources = ["*"]
  }
}

variable "role_policy_docs" {
  type        = list(string)
  description = "Policies associated with Role"
  default     = [
    "data.aws_iam_policy_document.role_1.json",
    "data.aws_iam_policy_document.role_2.json",
  ]
}

locals {
  role_policy_docs = { for s in var.role_policy_docs: index(var.role_policy_docs, s) => s}
}

resource "aws_iam_policy" "role" {
  for_each = local.role_policy_docs

  name        = format("RolePolicy-%02d", each.key)
  description = "Custom Policies for Role"

  policy = each.value
}

resource "aws_iam_role_policy_attachment" "role" {
  for_each   = { for p in aws_iam_policy.role : p.name => p.arn }
  role       = aws_iam_role.role.name
  policy_arn = each.value
}

此示例已简化为最基本的内容。策略文档是使用source_jsonoverride_json 约定动态生成的。我不能简单地将这些声明组合成一个单一的政策文件。

地形错误:

Error: "policy" contains an invalid JSON policy

  on role.tf line 35, in resource "aws_iam_policy" "role":
  35:   policy = each.value

【问题讨论】:

    标签: terraform amazon-iam


    【解决方案1】:

    这个:

    variable "role_policy_docs" {
      type        = list(string)
      description = "Policies associated with Role"
      default     = [
        "data.aws_iam_policy_document.role_1.json",
        "data.aws_iam_policy_document.role_2.json",
      ]
    }
    

    将这些默认值定义为字符串,所以你得到的是:

      + role_policy_docs = {
          + 0 = "data.aws_iam_policy_document.role_1.json"
          + 1 = "data.aws_iam_policy_document.role_2.json"
        }
    

    如果您尝试删除 data 块周围的引号,它将无效,因为您不能在默认定义中使用变量。相反,将您的策略​​文档分配给一个新的本地,并在您的 for 循环中使用该本地:

    locals {
      role_policies = [
        data.aws_iam_policy_document.role_1.json,
        data.aws_iam_policy_document.role_2.json,
      ]
      
    
      role_policy_docs = { 
        for s in local.role_policies : 
          index(local.role_policies, s) => s 
        }
    }
    

    【讨论】:

    • 谢谢@Tyler!关于不在默认定义中使用变量的澄清是我被绊倒的。
    猜你喜欢
    • 2022-01-19
    • 2016-06-05
    • 1970-01-01
    • 2018-09-29
    • 2020-12-26
    • 2020-09-17
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    相关资源
    最近更新 更多