遍历map并在Terraform中连接字符串



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

我的期望输出是:

  • s3://桶/name1/k1/abc/
  • s3://桶/name1/k2/def/
  • s3://桶/name2 k3/xyz/

但与目前的设置,我得到一个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个embedder 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是一个数组)。

相关内容

  • 没有找到相关文章

最新更新