Search code examples
amazon-web-servicesterraformterraform-provider-aws

Access the index of a map in for_each


I have a map that looks like this

variable "mysubnets" {
  type = map(string)
  default = {
    "subnet1" = "10.1.0.0/24"
    "subnet2" = "10.1.1.0/24"
  }
}

In my module I'm trying to place subnets in different availability zones in the same vpc

data "aws_availability_zones" "azs" {
  state = "available"
}

resource "aws_subnet" "test-subnets" {
  for_each = var.mysubnets
  cidr_block = "${each.value}"
  vpc_id = aws_vpc.myvpc.id
  availability_zone = data.aws_availability_zones.azs.names[index("${each.value}")]

  tags = {
    Name = "${each.key}"
  } 
}

I can get the key and value from the map no problem, but when trying to pick an availability zone I can't find how to change the value. Is there a way to get the index of a map, or create a counter for a number that increments?


Solution

  • Your data source is called azs, not available. So it should be:

    availability_zone = data.aws_availability_zones.azs.names[index("${each.value}")]
    

    Update:

    To use index with your var.mysubnets you can do as follows:

    resource "aws_subnet" "test-subnets" {
    
      for_each = {for idx, subnet in keys(var.mysubnets): 
                      idx => { 
                          name = subnet
                          cidr = var.mysubnets[subnet]
                      }
                 }
                 
      cidr_block = each.value.cidr
      vpc_id = aws_vpc.myvpc.id
      
      availability_zone = element(data.aws_availability_zones.azs.names, each.key)
    
      tags = {
        Name = each.value.name
      } 
    }