Azure Networking Blog articles

Azure Networking Blog articles

https://techcommunity.microsoft.com/t5/azure-networking-blog/bg-p/AzureNetworkingBlog

Azure Networking Blog articles

Programmatically Find Next Available CIDR for Subnet

Published

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!

Continue to website...

More from Azure Networking Blog articles

Related Posts