Search⌘ K

Foreach

Explore how to utilize the for_each construct in Terraform to create and manage multiple resources effortlessly. This lesson helps you understand transforming lists into sets, using special attributes like each.key, and applying changes dynamically, enabling more flexible and precise infrastructure deployments.

We'll cover the following...

Foreach

The for_each construct allows you to create a set of resources similar to what we have just seen before by using the count. A for_each statement is more useful when you are projecting a set of values into a set of resources though.

Project example

Let’s see an example:

C++
provider "aws" {
region = "us-east-2"
}
locals {
fruit = toset(["apple", "orange", "banana"])
}
resource "aws_sqs_queue" "queues" {
for_each = local.fruit
name = "queue-${each.key}"
}
output "queue-apple-name" {
value = aws_sqs_queue.queues["apple"].name
}

A few things ...