flatten
ネストしていない通常のオブジェクトであれば、for_each
でループさせることで各要素にアクセスできる。だけども、オブジェクトがネストしている場合、二重ループなどができない(難しい)のでその場合などに使える。
サンプル
下記の場合、pilotの部分がネストのオブジェクトになっている。
pilotを直接for_eachで取り扱うことができないので、一度local変数にflatten化した中間リソースを持つようにする。
なお、flattenはリストにのみ対応しているので、forでリストにしている。
main.tf
locals {
flattened_settings = flatten([
for machine_key, machine_number in var.settings : [
for pilot_key, pilot_value in machine_number.pilot : {
machine_key = machine_key
pilot_key = pilot_key
pilot_name = pilot_value.name
pilot_stage = pilot_value.stage
}
]
])
}
output "flattened_resources" {
value = local.flattened_settings
}
variables.tf
variable "settings" {
type = map(object({
name = string
pilot = map(object(
{
name = string
stage = number
}))
}
)
)
}
terraform.tfvars
settings = {
x131 = {
name = "calamity"
pilot = {
orga = {
name = "orga subnac"
stage = 2
}
}
}
x252 = {
name = "forbidden"
pilot = {
shani = {
name = "shani andras"
stage = 4
}
}
}
x370 = {
name = "raider"
pilot = {
crot = {
name = "crot buel"
stage = 4
}
}
}
}
実行結果
Outputs:
flattened_resources = [
{
"machine_key" = "x131"
"pilot_key" = "orga"
"pilot_name" = "orga subnac"
"pilot_stage" = 2
},
{
"machine_key" = "x252"
"pilot_key" = "shani"
"pilot_name" = "shani andras"
"pilot_stage" = 4
},
{
"machine_key" = "x370"
"pilot_key" = "crot"
"pilot_name" = "crot buel"
"pilot_stage" = 4
},
]
参考