Terraform

terraform count vs for_each

DevelopC 2023. 3. 7. 01:35
728x90

terraform count vs for_each

Terraform에서 count와 for_each는 모두 리소스 반복 생성을 위한 기능입니다. 하지만 둘은 다른 방식으로 동작합니다. count는 반복 횟수를 지정하는 숫자 형태의 값이며, 각 리소스에 인덱스가 자동으로 할당됩니다. 이 방식은 생성하려는 리소스 수가 고정되어 있을 때 유용합니다. for_each는 객체 형태의 값(맵)을 받으며, 각 맵 요소에 대해 리소스를 생성합니다. 이 방식은 동적으로 생성해야 하는 리소스 수가 있을 때 유용합니다.

 

리소스의 추가/삭제 없이 고정된 리소스를 사용하려면 count를 사용하고, 리소스 추가/삭제가 빈번하면 for_each를 사용하세요. 자세한 설명은 아래의 예제코드를 확인해보세요.

 

count

count를 사용한 예제코드 및 설명입니다.  아래의 코드는 list 변수를 사용하여 null_resource를 3개를 만드는 코드입니다.

variable "list" {
  default = ["one", "two", "three"]
}

resource "null_resource" "this" {
  count = length(var.list)

  triggers = {
    list_index = count.index
    list_value = var.list[count.index]
  }
}

위의 코드를 terraform apply하여 실행하면 나오는 결과입니다. count 사용으로 인해 null_resource.this의 인덱스가 숫자로 채워집니다.

null_resource.this[0]: Creating...
null_resource.this[1]: Creating...
null_resource.this[2]: Creating...
null_resource.this[0]: Creation complete after 0s [id=8071355031243219468]
null_resource.this[2]: Creation complete after 0s [id=1145044440732666892]
null_resource.this[1]: Creation complete after 0s [id=6536805642018644719]

코드를 변경하여 one과 two사이에 four를 추가하였습니다.

variable "list" {
  default = ["one", "four", "two", "three"]
}

resource "null_resource" "this" {
  count = length(var.list)

  triggers = {
    list_index = count.index
    list_value = var.list[count.index]
  }
}

terraform plan으로 확인한 결과입니다. count index가 변경되어 two, three에 해당되는 리소스를 삭제하고 다시 생성합니다.

$ terraform plan
null_resource.this[0]: Refreshing state... [id=8071355031243219468]
null_resource.this[1]: Refreshing state... [id=6536805642018644719]
null_resource.this[2]: Refreshing state... [id=1145044440732666892]

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
  + create
-/+ destroy and then create replacement

Terraform will perform the following actions:

  # null_resource.this[1] must be replaced
-/+ resource "null_resource" "this" {
      ~ id       = "6536805642018644719" -> (known after apply)
      ~ triggers = { # forces replacement
          ~ "list_value" = "two" -> "four"
            # (1 unchanged element hidden)
        }
    }

  # null_resource.this[2] must be replaced
-/+ resource "null_resource" "this" {
      ~ id       = "1145044440732666892" -> (known after apply)
      ~ triggers = { # forces replacement
          ~ "list_value" = "three" -> "two"
            # (1 unchanged element hidden)
        }
    }

  # null_resource.this[3] will be created
  + resource "null_resource" "this" {
      + id       = (known after apply)
      + triggers = {
          + "list_index" = "3"
          + "list_value" = "three"
        }
    }

Plan: 3 to add, 0 to change, 2 to destroy.

for_each

for_each를 사용한 예제코드 및 설명입니다.  count예제코드와 동일한 코드를 for_each를 사용하여 구현하였습니다.

variable "list" {
  default = ["one", "two", "three"]
}

resource "null_resource" "this" {
  for_each = toset(var.list)

  triggers = {
    list_index = each.key
    list_value = each.value
  }
}

위의 코드를 terraform apply하여 실행하면 나오는 결과입니다. for_each 사용으로 인해 null_resource.this의 인덱스가 value값으로 채워집니다.

null_resource.this["two"]: Creating...
null_resource.this["three"]: Creating...
null_resource.this["one"]: Creating...
null_resource.this["one"]: Creation complete after 0s [id=3808014950563960207]
null_resource.this["three"]: Creation complete after 0s [id=8083448573192777063]
null_resource.this["two"]: Creation complete after 0s [id=8955221205126061361]

코드를 변경하여 one과 two사이에 four를 추가하였습니다.

variable "list" {
  default = ["one", "four", "two", "three"]
}

resource "null_resource" "this" {
  for_each = toset(var.list)

  triggers = {
    list_index = each.key
    list_value = each.value
  }
}

terraform plan으로 확인한 결과입니다. for_each의 인덱스가 추가되어 four리소스만 생성합니다.

$ terraform plan
null_resource.this["three"]: Refreshing state... [id=8083448573192777063]
null_resource.this["two"]: Refreshing state... [id=8955221205126061361]
null_resource.this["one"]: Refreshing state... [id=3808014950563960207]

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # null_resource.this["four"] will be created
  + resource "null_resource" "this" {
      + id       = (known after apply)
      + triggers = {
          + "list_index" = "four"
          + "list_value" = "four"
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

결론

리소스의 추가/삭제 없이 고정된 리소스를 사용하려면 count를 사용하고, 리소스 추가/삭제가 빈번하면 for_each를 사용해야합니다.

728x90

'Terraform' 카테고리의 다른 글

Terraform으로 AWS EKS 클러스터 만들기  (0) 2022.09.30
Terraform state mv 사용하기  (0) 2022.09.21
Terraform으로 helm chart 배포하기  (0) 2022.09.20