Terraform - 展平嵌套地图
Terraform - flattening nested map
我目前有一个 terraform 对象声明如下:
locals {
x = {
a = [
{
p0 = "j"
p1 = "test-1"
p2 = 0
},
{
p0 = "k"
p1 = "test-2"
p2 = 0
}
]
b = [
{
p0 = "j"
p1 = "test-1"
p2 = 1
},
{
p0 = "k"
p1 = "test-3"
p2 = 0
}
]
}
}
我想做的是将结构展平,但我不知道这在 terraform 中是否可行。在我的例子中,我知道 p0 在它自己的数组中是唯一的,所以我应该能够为每条记录构造唯一的键。我想要的输出如下:
locals {
y = {
a-j {
p0 = "j"
p1 = "test-1"
p2 = 0
}
a-k {
p0 = "k"
p1 = "test-2"
p2 = 0
}
b-j {
p0 = "j"
p1 = "test-1"
p2 = 1
}
b-k {
p0 = "k"
p1 = "test-3"
p2 = 0
}
}
}
我已经通过将所有内容转换为列表、将其展平并使用计数来实现此功能,但我想保留密钥以防顺序在以后更改以防止不必要地删除资源。感谢您的帮助!
我认为以下内容应该能满足你的要求:
locals {
x = {
a = [
{
p0 = "j"
p1 = "test-1"
p2 = 0
},
{
p0 = "k"
p1 = "test-2"
p2 = 0
}
]
b = [
{
p0 = "j"
p1 = "test-1"
p2 = 1
},
{
p0 = "k"
p1 = "test-3"
p2 = 0
}
]
}
flat = merge([
for k1, v1 in local.x:
{
for v2 in v1:
"${k1}-${v2.p0}" => v2
}
]...)
}
这将导致 flat
为:
{
"a-j" = {
"p0" = "j"
"p1" = "test-1"
"p2" = 0
}
"a-k" = {
"p0" = "k"
"p1" = "test-2"
"p2" = 0
}
"b-j" = {
"p0" = "j"
"p1" = "test-1"
"p2" = 1
}
"b-k" = {
"p0" = "k"
"p1" = "test-3"
"p2" = 0
}
}
我目前有一个 terraform 对象声明如下:
locals {
x = {
a = [
{
p0 = "j"
p1 = "test-1"
p2 = 0
},
{
p0 = "k"
p1 = "test-2"
p2 = 0
}
]
b = [
{
p0 = "j"
p1 = "test-1"
p2 = 1
},
{
p0 = "k"
p1 = "test-3"
p2 = 0
}
]
}
}
我想做的是将结构展平,但我不知道这在 terraform 中是否可行。在我的例子中,我知道 p0 在它自己的数组中是唯一的,所以我应该能够为每条记录构造唯一的键。我想要的输出如下:
locals {
y = {
a-j {
p0 = "j"
p1 = "test-1"
p2 = 0
}
a-k {
p0 = "k"
p1 = "test-2"
p2 = 0
}
b-j {
p0 = "j"
p1 = "test-1"
p2 = 1
}
b-k {
p0 = "k"
p1 = "test-3"
p2 = 0
}
}
}
我已经通过将所有内容转换为列表、将其展平并使用计数来实现此功能,但我想保留密钥以防顺序在以后更改以防止不必要地删除资源。感谢您的帮助!
我认为以下内容应该能满足你的要求:
locals {
x = {
a = [
{
p0 = "j"
p1 = "test-1"
p2 = 0
},
{
p0 = "k"
p1 = "test-2"
p2 = 0
}
]
b = [
{
p0 = "j"
p1 = "test-1"
p2 = 1
},
{
p0 = "k"
p1 = "test-3"
p2 = 0
}
]
}
flat = merge([
for k1, v1 in local.x:
{
for v2 in v1:
"${k1}-${v2.p0}" => v2
}
]...)
}
这将导致 flat
为:
{
"a-j" = {
"p0" = "j"
"p1" = "test-1"
"p2" = 0
}
"a-k" = {
"p0" = "k"
"p1" = "test-2"
"p2" = 0
}
"b-j" = {
"p0" = "j"
"p1" = "test-1"
"p2" = 1
}
"b-k" = {
"p0" = "k"
"p1" = "test-3"
"p2" = 0
}
}