Terraform 0.12 - For each subnet-id in array, get cidr_block

I have a list of subnets IDs and I want to get an array of the cidr_blocks associated to each subnet.

variable "aws_subnet_ids" {
  type = list(string)
  default = ["subnet-aaaaaaaa","subnet-bbbbbbbb"]

desired_output = ['', '']

I’ve been fiddling around with for loops and count data for a quite a while for what should be a really simple problem. But I’m having a hard time finding an appropriate way to actually do this.

This seemed like a decent example to work off of, but you can’t actually use a for_each in a data source off a list of strings. https://www.terraform.io/docs/providers/aws/d/subnet_ids.html

data "aws_subnet" "example" {
  for_each = var.aws_subnet_ids
  cidr_blocks       = each.cidr_block

output "subnet_cidr_blocks" {
  value = [for s in data.aws_subnet.example : s.cidr_block]

You can’t use list with for_each in a resource, but you can convert lists into sets.

Consider doing a map of subnet_Id => cidr_block instead of a list, it will usually be easier to work with as you can then use for_each with that map to obtain a more stable configuration.

1 Like