获取 Terraform 中列表中元素的索引

获取 Terraform 中列表中元素的索引

在 Terraform 中如何计算列表中元素的索引?

例如:如果我们有这个变量:

variable "domains" {

  type = "list"

  default = [
    "tftesting.io",
    "tftesting.co",
  ]
}

我们如何计算“tftesting.io”的索引为“0”而“tftesting.co”的索引为“1”?

答案1

最终获胜者是:index(list, element)

variable "domains" {
  type = "list"

  default = [
    "tftesting.io",
    "tftesting.co",
  ]
}

output "co_index" {
  value = "${index(var.domains, "tftesting.co")}"
}

output "io_index" {
  value = "${index(var.domains, "tftesting.io")}"
}

最终结果:

$ terraform apply

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

co_index = 1
io_index = 0

相关内容