Terraform 使用';时会导致意外结果的回路地形;展平';和';元素';功能
我试图通过每隔一个元素将一个数组解析为两个数组 示例: [“托马斯1”、“托马斯2”、“托马斯3”、“托马斯4”、“托马斯5”] 拆分为两个新阵列: [“托马斯1”、“托马斯3”、“托马斯5”] 和 [“托马斯2”、“托马斯4”] 也许有更好的方法可以做到这一点,但在Terraform中,当我使用下面的代码时,我的第二个新数组得到了一个非常奇怪的结果。我完全弄不懂这是怎么可能的Terraform 使用';时会导致意外结果的回路地形;展平';和';元素';功能,terraform,Terraform,我试图通过每隔一个元素将一个数组解析为两个数组 示例: [“托马斯1”、“托马斯2”、“托马斯3”、“托马斯4”、“托马斯5”] 拆分为两个新阵列: [“托马斯1”、“托马斯3”、“托马斯5”] 和 [“托马斯2”、“托马斯4”] 也许有更好的方法可以做到这一点,但在Terraform中,当我使用下面的代码时,我的第二个新数组得到了一个非常奇怪的结果。我完全弄不懂这是怎么可能的 locals { hostnames = ["thomas1", "thomas2&
locals {
hostnames = ["thomas1", "thomas2", "thomas3", "thomas4", "thomas5"]
clusterA_range = range(0,length(local.hostnames),2)
clusterB_range = range(1,length(local.hostnames),2)
clusterA = flatten ( [ for i in local.clusterA_range : element(local.hostnames,(element(local.clusterA_range,i))) ] )
clusterB = flatten ( [ for x in local.clusterB_range : element(local.hostnames,(element(local.clusterB_range,x))) ] )
}
output "hostnames" {
value = local.hostnames
}
output "clusterA" {
value = local.clusterA
}
output "clusterB" {
value = local.clusterB
}
output "clusterA_range" {
value = local.clusterA_range
}
output "clusterB_range" {
value = local.clusterB_range
}
其结果是:
$ terraform apply
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
Terraform will perform the following actions:
Plan: 0 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
clusterA = [
"thomas1",
"thomas5",
"thomas3",
]
clusterA_range = [
0,
2,
4,
]
clusterB = [
"thomas4",
"thomas4",
]
clusterB_range = [
1,
3,
]
hostnames = [
"thomas1",
"thomas2",
"thomas3",
"thomas4",
"thomas5",
]
为什么clusterB[“thomas4”,“thomas4”]
Terraform版本v0.13.0-dev发生这种情况是因为您正在迭代范围的值,然后使用这些值再次选择范围值。如果要保持结构,必须在以下范围内迭代索引:
locals {
hostnames = ["thomas1", "thomas2", "thomas3", "thomas4", "thomas5"]
clusterA_range = range(0,length(local.hostnames), 2)
clusterB_range = range(1,length(local.hostnames), 2)
clusterA = flatten ( [
for idxA, i in local.clusterA_range :
element(local.hostnames,(element(local.clusterA_range, idxA))) ] )
clusterB = flatten (
[ for idxB, x in local.clusterB_range :
element(local.hostnames,(element(local.clusterB_range, idxB))) ] )
}
但是,对于您的特定示例,您可以简化选择:
clusterA = [for i in local.clusterA_range : element(local.hostnames, i) ]
clusterB = [ for x in local.clusterB_range : element(local.hostnames, x) ]
啊!现在这很有道理。非常感谢你。您的简化解决方案更加优雅@汤马斯:没问题。很高兴它成功了:-)这不是对你问题的直接回答,但我只是想指出,你在这里的预期目标似乎有点类似,以防这有助于简化解决方案。