Terraform - 将字符串附加到 for_each 中的对象

Terraform - Append a string to an object in a for_each

如何使用 for_each/* 附加到对象的末尾?目标是让 Terraform 遍历 resource_arns 列表并将 /* 添加到末尾。但是,我目前收到错误消息“模板插值无效”。

如果我有 resources = each.value.resource_arns,那么 Terraform 可以创建资源,但如果没有 /*,这是不需要的。

期望的结果是将资源创建为:

+ Action   = [
    + "s3:PutObject",
    + "s3:GetObject",
    + "s3:DeleteObject",
  ]
+ Effect   = "Allow"
+ Resource = "arn:aws:s3:::my-bucket-here/*"

错误

╷
│ Error: Invalid template interpolation value
│ 
│   on account-iam-policy/module/main.tf line 168, in data "aws_iam_policy_document" "this":
│  168:       resources = ["${each.value.resource_arns}/*"]
│     ├────────────────
│     │ each.value.resource_arns is list of string with 1 element
│ 
│ Cannot include the given value in a string template: string required.
╵

terragrunt.hcl

inputs = {
  service_accounts = {
    "aws-s3-bucket" = {
      name          = "my-s3-bucket"
      policy = {
        "s3-rw" = {
          resource_arns = ["arn:aws:s3:::my-bucket-here"] 
          policy_keys = ["aws_s3_rw_policy"]
        }
      }
    }
}

main.tf

data "aws_iam_policy_document" "this" {
  for_each = var.policy
  dynamic "statement" {
    for_each = contains(each.value.policy_keys, "aws_s3_rw_policy") ? ["apply"] : []
    content {
      effect = "Allow"

      actions = [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject"
      ]
 
      resources = ["${each.value.resource_arns}/*"]

    }
  }
}

variables.tf

variable "service_accounts" {
  type = map(object({
    name      = string

    policy = map(object({
      resource_arns = list(string)
      policy_keys   = list(string)
    }))

  }))
}

你必须遍历 resource_arns:

resources = [for arn in each.value.resource_arns: "${arn}/*"]