I need to programmatically determine the next available subnet address space within a given VNET CIDR range, when passed an object containing multiple subnets which could be of varying sizes.
The input we have at the moment is a list of objects which specify a list of virtual networks, as an example:
virtual_networks = [
{
location = "westeurope"
size = 24
subnets = [
{
type = "web"
size = 27
},
{
type = "app"
size = 26
},
{
type = "db"
size = 26
},
{
type = "private"
size = 27
}
]
}
]
The CIDR range for the VNET is obtained using a provider for Azure IPAM, based on the specified size of the VNET. This ensures that the CIDR range is available within our environment.
This is then passed to a local which determines the details for each subnet which we use to create the subnets:
subnets = var.virtual_network_enabled ? flatten([
for k, v in var.virtual_networks : [
for i, subnet in v.subnets : {
vnet_location = v.location
type = subnet.type
size = subnet.size
address_prefix = cidrsubnet(azureipam_reservation.virtual_network[v.location].cidr, subnet.size - v.size, i)
}
]
]) : []
The logic, using cidrsubnet, works fine if all subnets are the same size. This falls over when we pass different subnet sizes as per the example above.
Is there a better way to determine these subnet sizes? Have I missed a function that is going to do this for me?
Thanks in advance!