Add Subnets to Existing Azure VNET Using PowerShell

Following our previous blog post today we are going to show you how to modify an existing VNET in Azure and add new subnets using PowerShell.

Adding and removing subnets using the GUI is simple however when it comes to automating Azure and keeping all changes in a source control repository using PowerShell, Ansible or Terraform require a bit of coding.

About Azure VNET

Azure VNET is a cloud service that enables you to create a private network in the Microsoft Azure cloud. This can be used to connect your on-premises networks with Azure or to create a separate, isolated network for your applications and resources.

The Microsoft Virtual Network supports full Layer 3 connectivity between subnets within different virtual networks. This means that a subnet in one virtual network can be connected to a subnet in another virtual network over the public Internet.

Modify Azure VNET

To create an Azure VNET with PowerShell please visit the following post.

Modifying an existing Azure VNET with PowerShell is not a simple process sadly. In order to modify an existing VNET, we need first recreate the VNET with the changes in memory via PowerShell and then apply the changes.

This method is very different from other processes where we use a set command that set new values. with VNET changes we use the set cmdlet but we use it to set a new object as you will.

So first before we make changes, we need to make sure we know what we have in the current VNET.

In the cmdlets below, I’m going to add two subnets ( serverssubnet and dmz) to my existing VNET.

The appsssubnet already exist in the VNET however I still need to add it to the new VNET object I’m creating in memory. The updated VNET with the modified subnets is called updatedvent.

To wrap up all the changes and apply them using PowerShell I’m using the last line in the below code and use the set-AzVirtualNetwork command.

$appssubnet = New-AzVirtualNetworkSubnetConfig -Name servers -AddressPrefix "172.16.1.0/24"
$serversubnet = New-AzVirtualNetworkSubnetConfig -Name apps -AddressPrefix "172.16.2.0/24"
$dmz = New-AzVirtualNetworkSubnetConfig -Name dmz -AddressPrefix "172.16.3.0/24"
$updatedvnet = New-AzVirtualNetwork -Name MyVNET -ResourceGroupName vnetlab -Location australiasoutheast -AddressPrefix "172.16.0.0/16" -Subnet $serversubnet, $dmz, $appssubnet -Force:$true
$updatedvnet | Set-AzVirtualNetwork

After running the command PowerShell will update the existing VNET with the new subnets.

To remove a subnet we use the same process and we just need to create a new VNET object with the subnets we would like to keep.

,

Processing…
Success! You're on the list.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.