Terraform - Loop over list using for_each

Here is an example of how for_each can be used. In this example, the for_each loop only contains keys (no values). In this example, two Amazon Web Services (AWS) Virtual Private Cloud (VPC) will be created, my-vpc-foo and my-vpc-bar.

resource "aws_vpc" "my-vpc" {
  for_each = toset( ["foo", "bar"] )
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "my-vpc-${each.key}"
  }
}

 

In this example, the for_each loop contains keys and values. In this example, three Amazon Web Services (AWS) Virtual Private Cloud (VPC) will be created, my-vpc-us-east-2a and my-vpc-us-east-2b and my-vpc-us-east-2c, each with a unique CIDR block.

resource "aws_vpc" "my-vpc" {
  for_each = {
    "us-east-2a" = "10.11.1.0/22"
    "us-east-2b" = "10.11.2.0/22"
    "us-east-2c" = "10.11.3.0/22"
  }
  availability_zone = each.key
  cidr_block = each.value
  tags = {
    Name = "my-vpc-${each.key}"
  }
}

 

More commonly, instead of hard coding in values to loop over, you will be using values from a resource block or a data block. For example, let's say you have data blocks to get the JSON of the subnet's being used by an Amazon Web Services (AWS) Virtual Private Cloud (VPC).

data "aws_vpc" "default-vpc" {
  filter {
    name   = "tag:Name"
    values = ["default"]
  }
}

data "aws_subnets" "default-vpc-subnets" {
  filter {
    name = "vpc-id"
    values = [data.aws_vpc.default-vpc.id]
  }
}

 

output can be used to see the JSON that is stored in data.aws_subnets.default-vpc-subnets.

output "subnets" {
  value = data.aws_subnets.default-vpc-subnets
}

 

Which should return something like this, where the "ids" key contains the list of subnets.

subnets = {
  "filter" = toset([
    {
      "name" = "vpc-id"
      "values" = tolist([
        "vpc-014d2fcfa335d3c01",
      ])
    },
  ])
  "id" = "us-east-1"
  "ids" = tolist([
    "subnet-03f11417780f6cdbc",
    "subnet-09b70fa463fcd4a19",
    "subnet-0f35c3586e5090314",
    "subnet-03c64e403dc5bf18f",
    "subnet-0316e4d9fcd4efccc",
    "subnet-05727079637285f90",
  ])
  "tags" = tomap(null) /* of string */
  "timeouts" = null /* object */
}

 

And here is how you would loop over each subnet value.

resource "aws_efs_mount_target" "my-efs-mount-target" {
  for_each = toset(data.aws_subnets.default-vpc-subnets.ids)

  subnet_id = each.value
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter 1a94d in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |