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?

More than 1 year has passed since last update.

[Terraform Tips] Local Valueの値によってループでの処理を制御する

Last updated at Posted at 2023-11-28

どちらかというと備忘のためなので、雑な記事でご容赦ください。

Terraformでよくあるループ処理

locals {
    clouds = {
        aws = {
            company = "amazon"
            contury = "us"
        }
        azure = {
            company = "microsoft"
            contury = "us"
        }
        sakura = {
            company = "sakura-internet"
            contury = "jp"
        }    
    }
}

resource "sample_resource" "cloud_vender" {
    for_each = local.cloud

    description = "this is ${each.key} produced by ${each.value.company}"
    .....
}

Local Valueに作成するリソース分の変数を定義して、リソースをfor_eachでループさせることにより類似したリソースを複数作る方法です。

上の例だとcloudsにて定義された"aws", "azure", "sakura"の3つ分のリソースが作成されます。

こういうケースありませんか?

ではcountry="us"となっているものだけ、リソースを作成したいという場合はどうすればいいでしょうか?

こうしましょう。

resource "sample_resource" "cloud_vender" {
    for_each =  { for k, v in local.clouds : k => v if v.country == "us" }

    description = "this is ${each.key} produced by ${each.value.company}"
    .....
}

for文とifによるフィルタリングを利用することで、country="us"の値を持つ変数だけリソース作成の対象になります。

for文の中をカスタマイズすることで、色々応用ができます。

参考

for Expressions

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?