Utilizing Loops in Terraform

Rashad Ansari
5 min readJun 19, 2023

Summary

This article explores how loops in Terraform can simplify the management of resources and configurations. The article explains loop constructs like “for_each” and “count”, providing practical examples and best practices. By leveraging loops effectively, Terraform users can streamline infrastructure provisioning and scale deployments easily.

Loop Constructs in Terraform

Terraform provides two main loop constructs: “for_each” and “count”. These constructs allow developers to iterate over a collection of values or repeat a resource block a specific number of times.

for_each

This loop construct allows you to iterate over a map or a set of values. It’s especially useful when you have multiple instances of a resource that share similar properties but require unique configurations.

Example 1: Suppose you need to create multiple AWS S3 buckets with different configurations. Instead of writing separate resource blocks for each bucket, you can leverage the “for_each” loop to simplify the process.

variable "buckets" {
type = map
default = {
"bucket1" = { region = "us-west-1", acl = "private" },
"bucket2" = { region = "us-east-1", acl = "public-read" }
}
}

resource "aws_s3_bucket" "bucket" {
for_each = var.buckets

bucket = each.key
region = each.value.region
acl = each.value.acl
}

In this example, we define a variable called “buckets” as a map that contains two buckets, “bucket1” and “bucket2”. Each bucket has its own configuration, including the AWS region and access control list (ACL) settings.

The “aws_s3_bucket” resource block uses the “for_each” loop with the variable “buckets”. The loop creates separate S3 buckets for each key-value pair in the “buckets” map. Inside the loop, we access the key and values of each iteration using “each.key” and “each.value” respectively. This way, each bucket gets created with its unique name, region, and ACL settings.

Example 2: In scenarios where you have to manage multiple instances within an Auto Scaling Group (ASG), the “for_each” loop can come in handy.

variable "instances" {
type = map
default = {
"instance1" = {…

--

--

Rashad Ansari

Curious and continuously learning software engineer, driven by crafting innovative solutions with passion. Let’s collaborate to shape a better future!