sslhow.com

Quick Guide to use for_each in Terraform

for_each in Terraform is used to create multiple similar resources based on a set or a map. It helps to apply the same configuration to a group of resources efficiently.

Syntax:


resource "resource_type" "example" {
  for_each = { ... }

  # resource configuration
}

Using for_each with a Set of Strings:

For a set of strings, for_each can create a resource for each string.

Example:


variable "subnets" {
  description = "A set of subnets"
  type        = set(string)
  default     = ["subnet-1", "subnet-2", "subnet-3"]
}

resource "aws_subnet" "example" {
  for_each = var.subnets

  cidr_block = each.value
  # ... other configuration ...
}

Using for_each with a Map:

Iterate over a map when you need to specify multiple properties for each resource.

Example:


variable "instances" {
  description = "Map of instances"
  type = map(object({
    name  = string
    image = string
  }))
  default = {
    instance1 = { name = "instance-1", image = "ami-123456" }
    instance2 = { name = "instance-2", image = "ami-789012" }
  }
}

resource "aws_instance" "example" {
  for_each = var.instances

  name  = each.value.name
  ami   = each.value.image
  # ... other configuration ...
}

Accessing Resources Created with for_each:

To reference a specific resource:


resource_type.example[<key>]

Example:


aws_instance.example["instance1"]

for_each is a powerful tool in Terraform, allowing for dynamic and scalable infrastructure as code, reducing redundancy, and enhancing maintainability.

The for_each meta-argument is a powerful tool in Terraform that allows you to dynamically create multiple instances of a resource based on a list or map. This can be incredibly helpful for automating repetitive tasks and managing large deployments.

Here’s a quick guide to using for_each in Terraform:

1. Define the Data Source:

Example:

locals {
  servers = {
    web1 = {
      name = "web1"
      ip_address = "10.0.0.1"
    },
    web2 = {
      name = "web2"
      ip_address = "10.0.0.2"
    },
  }
}

2. Use for_each in the Resource Block:

Example:

resource "aws_instance" "web_server" {
  for_each = local.servers

  ami           = "ami-01234567"
  instance_type = "t2.micro"

  tags = {
    Name = each.value.name
  }
}

3. Accessing Elements within the Loop:

Example:

resource "aws_instance" "web_server" {
  for_each = local.servers

  ami           = "ami-01234567"
  instance_type = "t2.micro"

  tags = {
    Name = each.value.name
  }

  private_ip = each.value.ip_address
}

4. Supported Data Types:

for_each can work with various data types, including:

Here are some additional tips for using for_each:

By mastering for_each, you can significantly improve your Terraform workflow and automate complex deployments with ease.

Exit mobile version