生成要在 for_each 中使用的集合

Generation of a set to be used in for_each

有没有办法从整数生成 set?如果我们有一个 number_of_instances 参数被转换为设置为在 for_each 元参数中使用,那将很方便。结果,我们不需要写:

for_each = toset(["one", "two", "three",])

相反,我们只设置一个参数:

number_of_instances = 3

现在我想到了这个:

variable "number_of_instances" {
  type = number
  default = 0
}

locals {
  i = [
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
  ]
}

resource "null_resource" "main" {
  for_each = toset(slice(local.i, 0, var.number_of_instances))
  connection {
    name = each.key
  }
}

希望你能做到以下几点:

variable "number_of_instances" {
  default = 3
}

locals {
  numbers = ["one", "two", "three", "four", "five", "six"]
  number_set = slice(local.numbers, 0, var.number_of_instances)
}

然后使用:

for_each = toset(local.number_set)

当然numbers必须先pre-populated。