Skip to content

Loops

Loops are an essential part of programming, and Terraform provides a number of loop constructs that allow you to iterate over collections of resources, data sources, and variables.


One of the most common loop constructs in Terraform is the for_each expression. This expression allows you to create multiple instances of a resource or module based on a map or set of values.

Here’s an example:

variable "instance_names" {
type = set(string)
default = ["web-1", "web-2", "web-3"]
}
resource "aws_instance" "web" {
for_each = var.instance_names
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = each.key
}
}

In this example, we define a set of instance names as a variable. We then use the for_each expression to create an AWS EC2 instance for each name in the set. The tags parameter is set dynamically based on the instance name.

Another loop construct in Terraform is the for expression. This expression allows you to iterate over a list of values and perform some action on each value. Here’s an example:

variable "zones" {
type = list(string)
default = ["us-west-1a", "us-west-1b", "us-west-1c"]
}
locals {
availability_zones = [
for zone in var.zones :
{
name = zone
id = substr(zone, length(zone) - 1, 1)
}
]
}
output "availability_zones" {
value = local.availability_zones[*].name
}

In this example, we define a list of availability zones as a variable. We then use the for expression to create a local variable that maps each availability zone to an object with a name and an id property. The substr function is used to extract the last character of the zone name to get the zone ID. Finally, we use an output to extract the names of the availability zones.

Finally, Terraform provides a count meta-argument that allows you to create a fixed number of resource instances. Here’s an example:

resource "aws_subnet" "public" {
count = 3
vpc_id = aws_vpc.main.id
cidr_block = "10.0.${count.index}.0/24"
}

In this example, we create three AWS subnets with sequential IP address ranges. The count meta-argument is set to 3, so three instances of the aws_subnet resource are created.

By using loops, you can create more modular, flexible, and reusable infrastructure solutions. The for_each, for, and count constructs provide different ways of iterating over data, so you can choose the one that best suits your needs.