Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 606
CEamonn Avatar asked Oct 20 '25 19:10

CEamonn


1 Answers

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
  } 
}
like image 155
Marcin Avatar answered Oct 23 '25 09:10

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!