在 Terraform 中迭代地图并连接字符串

Iterate over map and concatenate string in Terraform

我想遍历映射变量并将单个字符串连接到 S3 子文件夹的单个字符串。

我的预期输出是:

但是在当前的设置下我得到一个 Cannot include the given value in a string template: string required. 是否有另一种方法可以遍历我的 source_names 变量或者我应该以不同的方式设置它?

main.tf s3_buckets modules

resource "aws_s3_bucket" "bucket" {
  bucket = var.bucket_name
  acl    = "private"

  tags = {
    Name = var.tag
  }
}

resource "aws_s3_object" "new_folders" {
  for_each = var.source_names
  bucket = aws_s3_bucket.bucket.id
  acl = "private"
  key = "${each.key}/${each.value.key_name}/${each.value.key_value}"
}


resource "aws_s3_bucket_public_access_block" "example" {
  bucket              = aws_s3_bucket.bucket.id
  block_public_acls   = true
  block_public_policy = true

}

variables.tf s3_buckets_module

variable "bucket_name" {
    description = "Name of the bucket"
    type = string
}

variable "tag" {
    description = "Resource tag"
    type = string
}

variable "source_names" {
    description = "key"
    type = map(object({
        key_name = list(string)
        key_value = list(string)
    }))
}

main.tf pipeline module

module "s3_bucket" {
    source = "../s3_buckets"
    bucket_name  = "tf-list-keys-bucket"
    tag          = "tf"
    source_names = {"name1" = {"key_name" = ["k1", "k2"], "key_value" = ["abc/", "def/"]},
                    "name2" = {"key_name" = ["k3"], "key_value" = ["xyz/"]}
    }
}

main.tf

module "pipeline" {
  
  source      = "../modules/pipeline"
}

迭代你的 source_names 需要你有 2 个嵌入器 for 循环:

resource "aws_s3_object" "new_folders" {
  for_each = toset(flatten([
    for key, value in var.source_names : [
      for key_name, key_values in value : [
        for key_value in key_values :
        "${key}/${key_name}/${key_value}"
    ]]
  ]))
  bucket = aws_s3_bucket.bucket.id
  acl    = "private"
  key    = each.value
}

您必须扁平化您的数据结构,否则 Terraform 将不知道要提供多少资源。您不能只将数组放在字符串中并期望 Terraform 对其进行迭代(例如:key = "${each.key}/${each.value.key_name}/${each.value.key_value}" - each.value.key_value 是一个数组)。