1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

terraformのflattenを使ってネストのオブジェクトを取り扱う

Last updated at Posted at 2024-10-11

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
  },
]

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?