Need help creating multiple AZ resources

I need to be able to create resources based on the names and numbers. I need to use the name for the ‘name’ in each resource and the ‘num’ for the ‘IP scope’ in the virtual network as one of the octets in the IP address.

This does not work:

variable "names" {
    default     = [
            name    = "name1"
            num     = 1
            name    = "name2"
            num     = 2

resource "azurerm_resource_group" "rg-customers" {
  for_each  = var.names
  name      = "TEST-rg-${var.names[each.key].name}"
  location  = "East US 2"
resource "azurerm_virtual_network" "vnet-customers" {
  for_each            = (var.names)
  name                 = "vnet-${}"
  location             = azurerm_resource_group.rg-customers[each.key].location
  resource_group_name = azurerm_resource_group.rg-customers[each.key].name
  address_space       = ["10.${each.value.num}.0.0/16"]
  dns_servers         = ["10.${each.value.num}.0.4/16", "10.${each.value.num}.0.5/16"]

Hi @oferg2,

When asking a question about an error you saw it’s helpful to include that full error message, so we can more easily identify what part of the configuration is causing the error.

With that said, I’m guessing the error you saw was with both of your for_each arguments due to var.names being a list rather than a map. If so, there are two main paths forward to address that.

The first path, if you’re able to change the interface of this module, would be to declare your variable as being a map of number instead of a list of objects:

variable "names" {
  type = map(number)
  default = {
    name1 = 1
    name2 = 2

With that structure, each.key will be the name and each.value will be the number.

If it’s important to retain the variable as a list for some reason, you can use a for expression to project it into a map instead:

variable "names" {
  type = list(object({
    name = string
    num  = number
  default = [
    { name = "name1", num = 1 },
    { name = "name2", num = 2 },

resource "azurerm_resource_group" "rg-customers" {
  for_each  = { for n in var.names : => n.num }

  name     = "TEST-rg-${var.names[each.key].name}"
  location = "East US 2"

The for expression in the for_each above will project the list of objects into a map of number shaped the same as the first example in this comment, so again you can use each.key to use the name and each.value to use the number.

Thank you so much for the response !
After I changed the variable as suggested but to a string type, and referencing ‘key’ and ‘value’ as needed, I still get an error:

The variable now looks like this:

I figured it out, it was a syntax issue.
name = “TEST-rg-${[each.value]}”

Changed to:
name = “TEST-rg-${each.value}”

Now it works :slight_smile:

You saved me, thanks a lot !!!