1
votes

I have the block of code below that creates a bunch of subnets based on a list of names and a list of address_prefixes.

resource "azurerm_subnet" "subnet" {
  count                     = "${length(var.subnet_names)}"
  name                      = "${element(var.subnet_names, count.index)}"
  resource_group_name       = "${var.vnet_rg_name}"
  virtual_network_name      = "${data.azurerm_virtual_network.vnet.name}"
  address_prefix            = "${element(var.subnet_prefixes, count.index)}"
  service_endpoints         = ["Microsoft.Sql","Microsoft.Storage","Microsoft.AzureCosmosDB"]
  network_security_group_id = "${data.azurerm_network_security_group.required_nsg.id}"
  route_table_id            = "${element(azurerm_route_table.routetable.*.id, count.index)}"
  depends_on                = ["azurerm_route_table.routetable"]
}

I am then trying to create some routes using a module but when I try to pass in values for variables using properties from a specific instance of the azurerm_subnet.subnet resource, it throws the error:

"module.insidedmzroutes.var.subnet_name: Resource 'azurerm_subnet.subnet' not found for variable 'azurerm_subnet.subnet.5.name'"

module "insidedmzroutes" {
  source           = "./modules/dmzroutes"
  subnet_name      = "${azurerm_subnet.subnet.5.name}"
  vnet_rg          = "${data.azurerm_resource_group.vnet_rg.name}"
  route_table_name = "${azurerm_route_table.routetable.5.name}"
  next_hop_ip      = "${cidrhost(azurerm_subnet.subnet.5.address_prefix, 4)}"
  subnet_names     = ["${var.subnet_names}"]
  subnet_prefixes  = ["${var.subnet_prefixes}"]
}

Does this not work or do I have the reference constructed incorrectly?

1
Does subnet_name="${azurerm_subnet.subnet.*.name[5]}" work?Adil B

1 Answers

1
votes

Please have a look at the Terraform interpolation syntax documentation, look for interpolation syntax.

The following would work (as indicated by Adil B):

subnet_name = "${azurerm_subnet.subnet.*.name[5]}" As with the splat syntax * you select all of the elements created using a count variable, which will then return a list, which you can select the correct element from [5].

However, why are you also passing along the entire list of subnets? Which subnets are these? It's not very clear from your code if these are the 5 subnets you created earlier or different ones. Are you creating an insidedmzroutes for every subnet? If so, I'd get rid of the subnet_name var and instead implement something like this in the resource inside the module:

count = "${length(var.subnet_names)}"
subnet_name = "${element(var.subnet_names, count.index)}"