We use powershell function to allocate available address prefixes in existing vnet in Azure. Once the function returns the available address prefixes(for example 11 addresses) it is passed as a variable into terraform code that creates the actual subnet and assignes the allocated range as a address_prefixes attribute. Because terraform first plans and then applies changes creates a time window, that during this window multiple release processes may try to allocated the same address prefixes and later on only the very first one would be able to apply this change, the rest would fail because the range is already occupied. For now we decided to move subnet creation into PowerShell code and since all those processes may be restricted to the same agent we can protect the function call by mutex and avoid multiple allocations of the same range.
$mtx = [Threading.Mutex]::new($false, "$($MoreArgs.SubKey)-vNet-94e668a02f304787b38584d1eae843a0")
$null = $mtx.WaitOne()
try
{
Add-PodVnetSubnet $metadata.sub_key $ctx.service.id $MoreArgs.PodName $metadata.env_type $maxipnumber $metadata.primary_location $SecondaryLocations
}
finally
{
if ($mtx)
{
$mtx.ReleaseMutex()
$mtx = $null
}
}
This solution seems to be very complex and wonky and I am trying to figure out if there is a better way of creating subnets in parallel on the same vnet?