I would like to get with Terraform the active address space of VNets for Azure in Terraform that have a certain tag. For this I thought I could use Resource data source for virtual networks:
data "azurerm_resources" "vnets"{
type = "Microsoft.Network/virtualNetworks"
required_tags = {
tag_name = "tag"
}
}
Then I realized that required attribute "address_space" belongs actually to the Virtual Networks Data Source (https://www.terraform.io/docs/providers/azurerm/r/virtual_network.html). Still I need to get the information about existing virtual networks from the Resources Data Source. So I tried nesting the data sources, but the following code does not work:
data "azurerm_virtual_network" "vnets"{
for_each = [for r in data.azurerm_resources.vnets.resources: {r.name = split("/", split("/resourceGroups", r.id))}]
name = each.key
resource_group_name = each.value
}
If that were to work, the idea would then be to determine the lowest possible VNet address space I can give to a new VNet based on the currently allocated VNet addresses (active_vnet_addresses
) and a predefined address space (eligible_vnet_addresses
) constrained by the number of resource groups (980=3*255+215) per subscription in Azure:
locals {
active_vnet_addresses = azurerm_virtual_network.vnets.address_space
eligible_vnet_addresses = concat([for s in range(1,255,1): "10.${s}.0.0/16"], [for s in range(1,255,1): "11.${s}.0.0/16"], [for s in range(1,255,1): "12.${s}.0.0/16"], [for s in range(1,215,1): "13.${s}.0.0/16"])
available_vnet_addresses = setsubtract(local.eligible_vnet_addresses, local.active_vnet_addresses)
available_vnet_numbers_sorted = sort([for a in local.available_vnet_addresses: split(".", a)[1]])
lowest_available_address_num = (length(local.available_vnet_numbers_sorted) == 0 ? "no more resource groups available" : local.available_vnet_numbers_sorted[0])
}
I am quite new to Terraform and this is my best effort, so I greatly appreciate suggestion on code improvements and would highly appreciate if someone could point me to a solution on how to get already active address spaces from Azure in Terraform.