Skip to content

Instantly share code, notes, and snippets.

@micklaw
Created March 20, 2021 09:49
Show Gist options
  • Save micklaw/66cbafad84524734f2f8fdc5e8c480e7 to your computer and use it in GitHub Desktop.
Save micklaw/66cbafad84524734f2f8fdc5e8c480e7 to your computer and use it in GitHub Desktop.
Get existing or find the next available Subnet on an Azure VNET
param (
$subnetName,
$vnetGroupName,
$vnetName,
$subnetMask
)
Write-Host "subnetName '$subnetName'" -ForegroundColor Green
Write-Host "vnetGroupName '$vnetGroupName'" -ForegroundColor Green
Write-Host "vnetName '$vnetName'" -ForegroundColor Green
Write-Host "subnetMask '$subnetMask'" -ForegroundColor Green
$names = az network vnet subnet list -g $vnetGroupName --vnet-name $vnetName --query [].[name,addressPrefix] -o json
$nameObject = [system.String]::Join(" ", $names) | ConvertFrom-Json
foreach ($name in $nameObject)
{
$azureName = $name[0]
$address = $name[1]
if ($azureName -eq $subnetName) {
Write-Host "Found existing subnet: $address. Setting env variable 'Devops:Terraform:CIDR'" -ForegroundColor Green
echo "##vso[task.setvariable variable=Devops:Terraform:CIDR]$address"
exit 0
}
}
for ($io = 0; $io -lt 255; $io+=1)
{
# grab the first address on increments on
for ($i = 0; $i -lt 255; $i+=32)
{
$found = $false
$cidr = [string]::Format($subnetMask, $io, $i) #10.100.{0}.{1}/27
foreach ($name in $nameObject)
{
if ($cidr -eq $name[1]) {
$found = $true
}
}
if ($found -eq $false) {
Write-Host "Claiming available subnet: $cidr. Setting env variable 'Devops:Terraform:CIDR'" -ForegroundColor Green
echo "##vso[task.setvariable variable=Devops:Terraform:CIDR]$cidr"
exit 0
}
}
}
Write-Host "No subnets available to be created in $subnetMask" -ForegroundColor Green
exit 1
@micklaw
Copy link
Author

micklaw commented Mar 20, 2021

I run this via a Azure CLI Task in Azure DevOps. When it finds or identifies the next available subnet, it sets an environment variable for Terraform to pickup called ‘DevOps:Terraform:CIDR’.

For a passed in subnet mask like: 10.100.{0}.{1}/27

This will loop the third octet by one and the fourth octet by 32 given it is a /27 CIDR passed in.

You could probably calculate this out based on the CIDR passed in but we knew what size we needed, so was fine to hardcode it given PaaS services in Azure can only join a /27 as minimum.

Hope it helps someone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment