LoginSignup
4
2

More than 5 years have passed since last update.

terraform で入れ子ループ

Posted at

TL;DR

code

variable "asc" {
  type = "list"

  default = [
    "a",
    "b",
    "c",
    "d",
  ]
}

variable "desc" {
  type = "list"

  default = [
    "z",
    "y",
    "x",
  ]
}

// want
// a_z, a_y, a_x,
// b_z, b_y, b_x,
// c_z, c_y, c_x,
// d_z, d_y, d_x

locals {
  counter = {
    asc  = "${length(var.asc)}"
    desc = "${length(var.desc)}"
  }
}

// 要諦はasc(4)*desc(3)=count(12), index/asc(4)の余りとindex/asc(4)
resource "local_file" "foo" {
  count    = "${local.counter["asc"] * local.counter["desc"]}"
  content  = "ok"
  filename = "${path.module}/file_${var.asc[count.index % local.counter["asc"]]}-${var.desc[count.index / local.counter["asc"]]}.txt"
}

蛇足

  • 正確には terraform が順番どおりにやってくれないので入れ子ループとは呼びにくい
  • AWS で VPC Peering を考えた時にVPC間のルートテーブルとサブネットのIDをぶん回す時に使用した
  • もっとも、最終的にそれはVPC CIDRで接続することにしたのでお蔵入りになったのだけれど
  • 捨てるのももったいないのでサンプルにして残してみた
4
2
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
4
2