【Terraform】Terraform ~ ループ ~

■ はじめに

Terraform で ループをする方法についてまとめておく。
ループは、同じリソースを複数作成するのに役立つ。

目次

【1】count
【2】for_each
 1)toset
【3】for

【1】count

https://developer.hashicorp.com/terraform/language/meta-arguments/count

resource "aws_instance" "server" {
  # create four similar EC2 instances
  count = 4

  ami           = "ami-a1b2c3d4"
  instance_type = "t2.micro"

  tags = {
    Name = "Server ${count.index}"
  }
}

【2】for_each

https://developer.hashicorp.com/terraform/language/meta-arguments/for_each

resource "aws_iam_user" "the-accounts" {
  # map型またはset型しか使うことが出来ないため、toset関数を使う
  for_each = toset( ["Todd", "James", "Alice", "Dottie"] )
  name     = each.key
}

【Terraform】(初心者向け)for_eachの使い方(実例つき) - 自由気ままに書いちゃおう

1)toset

* set型(集合)に変換

https://developer.hashicorp.com/terraform/language/functions/toset
使用上の注意

* 重複排除
* 要素の順序が保証されない

【3】for

https://zenn.dev/wim/articles/terraform_loop

例1:List

locals {
  list = ["Hello", "World"]
}

output "output_list" {
  # [構文]
  # for <ITEM> in <LIST> : <OUTPUT>
  value = [for element in local.list : upper(element)]
}

# Outputs:
#
# output_list = [
#  "HELLO",     
#  "WORLD",     
# ]              

例2:Map

locals {
  mapper = {
    "key1" = "Hello"
    "key2" = "World"
  }
}

output "output_list" {
  # [構文]
  # for <KEY>,<VALUE> in <MAP> : <OUTPUT>
  value = [for key, value in local.mapper : "${key} is the ${value}"]
}

# Outputs:
#
# output_list = [
#   "key1 is the Hello",
#   "key2 is the World",
# ]

参考文献

https://tellme.tokyo/post/2022/06/12/terraform-count-for-each/

関連記事

Terraform ~ 環境構築編 ~
https://dk521123.hatenablog.com/entry/2023/04/05/000224
Terraform ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2019/12/09/222057
Terraform ~ 基本編 ~
https://dk521123.hatenablog.com/entry/2023/05/03/000000
Terraform ~ 条件分岐 ~
https://dk521123.hatenablog.com/entry/2024/08/13/134030
Terraform ~ Terraformあれこれ ~
https://dk521123.hatenablog.com/entry/2023/05/15/205352