DEV Community

Cover image for How to use for each in Terraform
Dennis Groß (he/him)
Dennis Groß (he/him)

Posted on

How to use for each in Terraform

The for_each meta argument can be used to remove redundancies from code blocks.

You can apply for_each on a data structure such as a

  • set
  • list
  • map

It is an alternative for the count meta argument and is mutually exclusive with count.

for_each on Sets

You can iterate over a set of values with the for_each meta argument as shown below.

resource "aws_subnet" "subnet_data2" {

  for_each = toset(local.cidrs)

  vpc_id                  = aws_vpc.main.id
  map_public_ip_on_launch = false

  cidr_block = each.key 
  availability_zone = "eu-central-1b"
}
Enter fullscreen mode Exit fullscreen mode

for_each on Lists

A more sophisticated way of using for_each is by defining a block with additional values.

This is especially useful since resource blocks do not allow you to define locals are some other kind of re-usable variables.

You can do that in the for_each block instead like shown with the idx value.

locals {
  cidrs = ["10.0.0.0/24", "10.0.1.0/24", "10.0.2.0/24"]
}

resource "aws_subnet" "subnet_data" {

  for_each = {
    for c in local.cidrs : c => {
      idx = index(local.cidrs, c)
    }
  }

  vpc_id                  = aws_vpc.main.id
  map_public_ip_on_launch = false

  cidr_block = each.key 
  availability_zone = element(var.availability_zones, each.value.idx)

  tags = {
    Name        = "${var.vpc_name}-subnet-data-${each.value.idx}"
    Environment = var.environment
  }
}
Enter fullscreen mode Exit fullscreen mode

for_each on Maps

You can use the keys or values function for a for_each block.

resource "aws_subnet" "subnet_data" {

  for_each = toset(local.cidrs.keys)

  vpc_id                  = aws_vpc.main.id
  map_public_ip_on_launch = false

}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)