Terraform: Create a map of subnet IDs in Azure


The subnets accessor in the azurerm_virtual_network Terraform data source returns a list of subnet names only. In most cases however, you will need to use a or multiple subnet IDs, for instance when deploying virtual machines. Instead of creating a new datasource (for possibly a small list of subnets) for each virtual machine you want to deploy, creating a locals map, which can be looked up afterwards, is going to be faster on the apply run.

Create a list of the existing virtual network subnets:

data azurerm_subnet "subnets" {
  count = length(data.azurerm_virtual_network.my_vnet.subnets)

  name                 = data.azurerm_virtual_network.my_vnet.subnets[count.index]
  virtual_network_name = var.vnet_name
  resource_group_name  = var.resource_group

locals {
  subnets = tomap({
      for snet in data.azurerm_subnet.subnets: snet.name => snet.id

In the above example, we first loop over all subnet names, returned by data.azurerm_virtual_network.my_vnet.subnets, to create a list of Azure virtual network subnet objects.

Afterwards we create a locals map called subnets, which contains mapping like “subnet name points to subnet ID”.

Finally, when creating Azure network interfaces with an IP configuration, you can easily lookup the correct subnet ID based on the subnet name (which you might have configured per virtual machine)

resource "azurerm_network_interface" "my_nic" {
  ip_configuration {
    subnet_id = lookup(local.subnets, "my_subnet_name")
Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Previous Post

Time based network access control on OpenBSD

Next Post

Terraform and libvirt nodes

Related Posts