1

在 Terraform 中,我需要将输入数据结构从例如:

vip_lists = [
    ["1.0.1.1", "1.0.1.2", "1.0.1.3", "1.0.1.4"]
    ["1.0.2.1", "1.0.2.2", "1.0.2.3", "1.0.2.4"]
    ["1.0.0.1", "1.0.0.2", "1.0.0.3", "1.0.0.4"]
]

产生这样的输出:

vip_sets = [
    ["1.0.1.1", "1.0.2.1", "1.0.0.1"]
    ["1.0.1.2", "1.0.2.2", "1.0.0.2"]
    ["1.0.1.3", "1.0.2.3", "1.0.0.3"]
    ["1.0.1.4", "1.0.2.4", "1.0.0.4"]
]

所以本质上,我需要获取列表的输入列表并创建一个输出,该输出再次是列表列表,但其第 0 个列表是输入中每个列表的第 0 个元素的列表......然后再次相同第一个等等。我无法提前知道输入中有多少个列表或它们会有多长时间,但如果有帮助,我们可以假设这些列表的长度都相同。

我已经尝试了几乎所有我能想到的并在网上搜索,但没有运气。非常欢迎所有建议!

4

2 回答 2

1

我曾经为github.com/mineiros-io上的一个模块的列表长度不同的列表编写了这个版本,我们使用这种转换来创建二维资源集count。(那些没有使用 atm,因为我们将它们转换为与 ressource level 一起使用的地图for_each)。

locals {
  matrix = [
    ["1.0.1.1", "1.0.1.4"],
    ["1.0.2.1", "1.0.2.2", "1.0.2.3", "1.0.2.4"],
    ["1.0.0.1", "1.0.0.3", "1.0.0.4"]
  ]

  row_lengths = [
    for row in local.matrix : length(row)
  ]

  max_row_length = max(0, local.row_lengths...)

  output = [
    for i in range(0, local.max_row_length) : [
      for j, _ in local.matrix : try(local.matrix[j][i], null)
    ]
  ]

  output_compact = [
    for i in range(0, local.max_row_length) : compact([
      for j, _ in local.matrix : try(local.matrix[j][i], null)
    ])
  ]
}

output "matrix" {
  value = local.output
}

output "compact" {
  value = local.output_compact
}

它可以处理动态列表大小并将它们输出紧凑或填充null值:

Outputs:

compact = [
  [ "1.0.1.1", "1.0.2.1", "1.0.0.1" ],
  [ "1.0.1.4", "1.0.2.2", "1.0.0.3" ],
  [ "1.0.2.3", "1.0.0.4" ],
  [ "1.0.2.4" ],
]

matrix = [
  [ "1.0.1.1", "1.0.2.1", "1.0.0.1" ],
  [ "1.0.1.4", "1.0.2.2", "1.0.0.3" ],
  [ null,      "1.0.2.3", "1.0.0.4" ],
  [ null,      "1.0.2.4", null      ],
]

我知道答案已经被接受,但也许有人仍然可以使用这个动态版本。

于 2020-11-05T01:09:19.387 回答
1

这有点可怕,但它有效(虽然我还没有测试如果它vip_lists是空的会做什么。可能会崩溃,因为我正在索引vip_lists[0]而不检查):

locals {
  vip_lists = [
    ["1.0.1.1", "1.0.1.2", "1.0.1.3", "1.0.1.4"],
    ["1.0.2.1", "1.0.2.2", "1.0.2.3", "1.0.2.4"],
    ["1.0.0.1", "1.0.0.2", "1.0.0.3", "1.0.0.4"]
  ]

  vip_sets = [for i in range(0, length(local.vip_lists[0])): [for j in range(0, length(local.vip_lists)): local.vip_lists[j][i]]]
}

output "vip_sets" {
  value = local.vip_sets
}
$ terraform apply
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

vip_sets = [
  [
    "1.0.1.1",
    "1.0.2.1",
    "1.0.0.1",
  ],
  [
    "1.0.1.2",
    "1.0.2.2",
    "1.0.0.2",
  ],
  [
    "1.0.1.3",
    "1.0.2.3",
    "1.0.0.3",
  ],
  [
    "1.0.1.4",
    "1.0.2.4",
    "1.0.0.4",
  ],
]
于 2020-11-03T22:37:04.813 回答