terraform

Terraform get list index on for_each


Terraform newbie here. I'd like to iterate a list using for_each, but it seems like the key and value are the same:

provider "aws" {
  profile = "default"
  region  = "us-east-1"
}

variable "vpc_cidrs" {
  default = ["10.0.0.0/16", "10.1.0.0/16"]
}

resource "aws_vpc" "vpc" {
  for_each             = toset(var.vpc_cidrs)
  cidr_block           = each.value
  enable_dns_hostnames = true
  tags                 = { Name = "Company0${each.key}" }
}

I'd like the tag Name to be "Name" = "Company01" and "Name" = "Company02" but according to terraform apply, I get: "Name" = "Company010.0.0.0/16" and "Name" = "Company010.1.0.0/16" What am I missing?


Solution

  • Found an easy solution using the index function:

    tags = { Name = "Company0${index(var.vpc_cidrs, each.value) + 1}" }