循环遍历字符串 terraform 列表

问题描述 投票:0回答:1

我得到了一个 terraform 资源输入,需要一个字符串输入列表,例如“words = list(string)”。我在variable.tf中创建了一个列表变量

variable "mywords" {
  type        = list
  default = ["simple","but","lovely"]
}

在main.tf

resource "provider_resource" "example" {
  words = var.mywords
}

我想在单词输入中单独运行列表中的每个字符串。如果我按所示运行它,它将所有列表字符串内容放入单词输入中。

terraform
1个回答
1
投票

由于列表是集合,为了为每个集合项创建资源,您需要使用

count
for_each
。根据您的用例,两者都可以工作。如果您决定使用
count
,代码应如下所示:

resource "provider_resource" "example" {
   count = length(var.mywords)
   words = var.mywords[count.index]
}

或者,如果您想使用

for_each
,则需要将变量重新创建为
set(string)
或使用显式类型转换:

resource "provider_resource" "example" {
   for_each = toset(var.mywords)
   words    = each.value # or each.key, since set does not have index numbers
}

如果您选择将变量重新声明为

set(string)
,则以下操作应该有效:

variable "mywords" {
  type    = set(string)
  default = ["simple","but","lovely"]
}

resource "provider_resource" "example" {
   for_each = var.mywords
   words    = each.value # or each.key, since set does not have index numbers
}

最后但并非最不重要的一点是,您应该始终小心参数期望的类型。在这种情况下,看起来应该向

words
传递一个列表。如果是这种情况,则上面必须通过在单个值周围使用方括号来解释这一点:

resource "provider_resource" "example" {
   count = length(var.mywords)
   words = [var.mywords[count.index]]
}

使用

for_each
时:

resource "provider_resource" "example" {
   for_each = toset(var.mywords)
   words    = [each.value] # or each.key, since set does not have index numbers
}
resource "provider_resource" "example" {
   for_each = var.mywords
   words    = [each.value] # or each.key, since set does not have index numbers
}
© www.soinside.com 2019 - 2024. All rights reserved.