Loading...

Programmatically Find Next Available CIDR for Subnet

Programmatically Find Next Available CIDR for Subnet

Introduction

I've had several customers who, after automating their Azure Infrastructure as Code (IaC), have asked how they can easily find the next available CIDR range for a given subnet size. This is not a task automation can easily do. Keep reading for an explanation of how it works.


Deploying the Code

The code for the Function App can be found in GitHub here. I wrote it using Visual Studio 2019.

 

Azure Function App

I created the Function App as a Windows .NET instance. It has “Anonymous” as its Authorization Level – if you use a different level you’ll have to do additional work to allow access to it.

 

After synchronizing the code from Visual Studio to GitHub, I used the “Publish” wizard in Visual Studio to deploy the code to Azure. I used the steps outlined in this documentation. This wizard generated a YAML workflow which was uploaded to GitHub and powered an Action. As a result, any code changes committed to the target GitHub branch are automatically built and deployed to the Function App.

 

Once the Function App is created and the code deployed via GitHub Actions, I went to the “Identity” blade and created a system-assigned managed identity so that the Function App had access to the target virtual network resources.

 

ManagedIdentity.jpg

 

I then gave it “Reader” access at the subscription level; you could scope it down to a more focused target such as a resource group or groups as desired.

 

RBAC.jpg

 

If you don’t correctly create the Function App’s managed identity you will get an error in the browser similar to the following:

 

 

 

{ "code": "500", "message": "InternalServerError, DefaultAzureCredential failed to retrieve a token from the included credentials. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/defaultazurecredential/troubleshoot\r\n- EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot\r\n- ManagedIdentityCredential authentication unavailable. Multiple attempts failed to obtain a token from the managed identity endpoint.\r\n- Visual Studio Token provider can\u0027t be accessed at .IdentityService\\AzureServiceAuth\\tokenprovider.json\r\n- Stored credentials not found. Need to authenticate user in VSCode Azure Account. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/vscodecredential/troubleshoot\r\n- Azure CLI not installed\r\n- PowerShell is not installed." }

 

 

 

 

If you create the managed identity, but fail to give it “Reader” access to the specified virtual network, you will get an error like this in the browser:

 

 

 

{ "code": "500", "message": "InternalServerError, The client \u0027xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\u0027 with object id \u0027xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\u0027 does not have authorization to perform action \u0027Microsoft.Resources/subscriptions/read\u0027 over scope \u0027/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\u0027 or the scope is invalid. If access was recently granted, please refresh your credentials.\r\nStatus: 403 (Forbidden)\r\nErrorCode: AuthorizationFailed\r\n\r\nContent:\r\n{\u0022error\u0022:{\u0022code\u0022:\u0022AuthorizationFailed\u0022,\u0022message\u0022:\u0022The client \u0027xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\u0027 with object id \u0027xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\u0027 does not have authorization to perform action \u0027Microsoft.Resources/subscriptions/read\u0027 over scope \u0027/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\u0027 or the scope is invalid. If access was recently granted, please refresh your credentials.\u0022}}\r\n\r\nHeaders:\r\nCache-Control: no-cache\r\nPragma: no-cache\r\nx-ms-failure-cause: REDACTED\r\nx-ms-request-id: a509a6e2-238e-43fe-8531-c3ede7fb4df8\r\nx-ms-correlation-request-id: REDACTED\r\nx-ms-routing-request-id: REDACTED\r\nStrict-Transport-Security: REDACTED\r\nX-Content-Type-Options: REDACTED\r\nDate: Thu, 24 Mar 2022 15:34:52 GMT\r\nConnection: close\r\nContent-Type: application/json; charset=utf-8\r\nExpires: -1\r\nContent-Length: 398\r\n" }

 

 

 

 

Usage

This Azure Function takes the following parameters as input and returns the first CIDR range in the given virtual network that matches the specified size.

  • Subscription ID
  • Virtual Network Name
  • Resource Group Name (containing the above VNet)
  • Desired CIDR Size of New Subnet (between 2 and 29)

 

Request Details

Requests to the Function App take the following format:

 

 

 

https://{{pathToFunctionApp}}?subscriptionId={{subscriptionId}}&resourceGroupName={{resourceGroupName}}&virtualNetworkName={{virtualNetworkName}}&cidr={{cidr}}

 

 

 

 

Response Details

There are two main response formats: one for a successful call, and one for errors.


Successful API Call

If your API call to the Function App is successful, you will receive a 200 HTTP response code and JSON that is similar to the following:

 

 

 

 

{ "name": "VNetUSNorthCentral", "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/VNets/providers/Microsoft.Network/virtualNetworks/VNetUSNorthCentral", "type": "Microsoft.Network/virtualNetworks", "location": "northcentralus", "proposedCIDR": "10.100.4.0/24" }

 

 

 


The CIDR you want for your new subnet is contained in the "proposedCIDR" field.


Failed API Call

There are two main reasons why your call may not succeed:
1. You pass in an invalid parameter. That will result in an HTTP 400 response that will look something like this:

 

 

{ "code": "400", "message": "BadRequest, Invalid CIDR: 2e" }

 

 

 

2. The specified virtual network does not have sufficient address space left for creation of a subnet of the desired size. For this error you will receive an HTTP 404 error, and a response similar to this:

 

 

{ "code": "404", "message": "NotFound, VNet VNets/VNetUSNorthCentral cannot accept a subnet of size 15" }

 

 

 


Conclusion

I hope you find this Function App helpful in automating your Azure virtual network deployments. Please let me know about any bugs or enhancements that should be addressed!

Published on:

Learn more
Azure Networking Blog articles
Azure Networking Blog articles

Azure Networking Blog articles

Share post:

Related posts

Routing options for VMs from Private Subnets

Virtual Machines deployed in Azure used to have Default Outbound Internet Access. Until today, this allows virtual machines to connect to...

1 year ago

Secure, High-Performance Networking for Data-Intensive Kubernetes Workloads

The intersection of Generative AI and cloud computing has been transforming how organizations build and manage their infrastructure. The deman...

1 year ago

Network Connectivity for RISE with SAP S/4HANA Cloud Private Edition on Azure

In this article, we will explore different ways to connect to RISE with SAP S/4HANA Cloud Private Edition deployment on Azure, guiding yo...

1 year ago

Optimize Azure Landing Zone with Azure Virtual Network Manager IP Address Management

Optimize Azure Landing Zone with Azure Virtual Network Manager IP Address Management What you will learn from this blog This blog explores how...

1 year ago

ExpressRoute Metro is now generally available!!

We are excited to announce general availability of ExpressRoute Metro, a new private connectivity architecture designed to enhance network res...

1 year ago

ExpressRoute guided configuration of multi-site circuits and connections is generally available

ExpressRoute guided experience for configuring multi-site resiliency circuits and connections is generally available in Azure public cloud. Th...

1 year ago

Manage NSG association on Subnets via Azure Policy

  In this blog article, we will cover how to deny the creation of a subnet in a Virtual Network if the subnet does not have a Network Sec...

1 year ago

Effortless Private Endpoint Management in Azure Landing Zones: A Streamlined and Compliant Approach

1. Challenge In Azure Landing Zones, the network infrastructure, including components like VNET Gateways and ExpressRoute circuits, is part of...

1 year ago

Unlocking Secure VM Connectivity with Azure Bastion

In today’s digital landscape, where security breaches are an unfortunate reality, safeguarding sensitive data and infrastructure has become mo...

1 year ago

Use cases of Advanced Network Observability for your Azure Kubernetes Service clusters

Introduction  Advanced Network Observability is the inaugural feature of the Advanced Container Networking Services (ACNS) suite bringing...

2 years ago

Newsletter

Get the latest Dynamics 365 and Power Platform content in your inbox

A curated digest of community blogs, product news, videos, and podcasts — delivered without the noise.

Weekly updates Unsubscribe anytime Fresh community picks
We use your email only for the newsletter and you can unsubscribe at any time.
By subscribing, you agree to the privacy policy.