Choosing the Right Terraform Loop: count vs for_each

Terraform is a popular infrastructure as code (IaC) tool that allows you to manage and automate your infrastructure resources. One of the key features of Terraform is its ability to create multiple resources in a single go, with the help of loops. In Terraform, there are two main loop constructs: count and for_each. Understanding when to use each of these constructs is crucial for writing efficient and scalable Terraform code.

When to Use count

The count argument is used to create a specified number of identical resources. For example, if you want to create three identical virtual machines (VMs), you would use the count argument like this:

resource "aws_instance" "example" {
  count = 3
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

The count argument is especially useful when you want to create a fixed number of resources, regardless of their state or configuration. Additionally, count can be used in combination with var.count to create a dynamic number of resources, based on user input or external data.

When to Use for_each

The for_each argument, on the other hand, is used to create resources based on a map or set of strings. Unlike count, which creates identical resources, for_each allows you to create unique resources based on the keys in the map or set. For example, if you want to create a unique S3 bucket for each environment in your organization, you would use for_each like this:

locals {
  environments = {
    dev  = "dev-bucket"
    prod = "prod-bucket"
    qa   = "qa-bucket"
  }
}

resource "aws_s3_bucket" "example" {
  for_each = local.environments
  bucket = each.value
}

The for_each argument is especially useful when you want to create unique resources based on specific data or conditions. Additionally, for_each can be used in combination with var.environments to create resources based on user input or external data.

In conclusion, count and for_each are two essential loop constructs in Terraform that can be used to create multiple resources in a single go. Understanding when to use each of these constructs is crucial for writing efficient and scalable Terraform code. Whether you want to create a fixed number of identical resources or unique resources based on specific data or conditions, Terraform’s count and for_each arguments have you covered."

Recent Articles

blog-image
A Comprehensive AWS Resource Tagging Strategy

Tagging is a powerful tool that provides control, visibility, and streamlined management of resources.

blog-image
Parallelizing Infrastructure Management: The Terrahaxs Advantage

A major limitation of existing Terraform CI/CD tools in the number of projects you are able to plan/apply simultaneously.

blog-image
Choosing the Right Terraform Loop: count vs for_each

Terraform is a popular infrastructure as code (IaC) tool that allows you to manage and automate your infrastructure resources.