In Azure IaaS, Virtual network is required to enable communications between resources such as VM’s, load balancers, gateways etc.
This article shows how to create a virtual network resource and subnets in Azure.
Create Azure Virtual Network and Subnet using PowerShell
Create a Virtual network with address prefix 172.17.0.0/16 with 2 subnets. One subnet having network 172.17.1.0/24 and second network 172.17.10.0/24
Step – 1: Login to Azure
Connect-AzAccount
Executing the above cmdlet brings a browser popup. Enter the azure credential to complete the login.
Step – 2: Create a Resource Group
$resource_locaton_main = 'Central US'
$resourceGroup_Name = "RG-MainSite"
#Create new Resource Group
New-AzResourceGroup -Name $resourceGroup_Name -Location $resource_locaton_main
Resource group named “RG-MainSite will be created in Central US location”
Step -3: Create virtual network with one subnet(internal subnet). Second subnet(DMZ) will be added after creating the virtual network.
Note: Both the subnets can be created along with virtual network.
$vnet_Name = "vnet-main"
$vnet_Prefix = "172.17.0.0/16"
$vsubnet_int = "172.17.1.0/24"
#Create a Vnet and Subnet
$subnetInternal = New-AzVirtualNetworkSubnetConfig -Name "v-subnet-int" `
-AddressPrefix $vsubnet_int
New-AzVirtualNetwork -Name $vnet_Name -AddressPrefix $vnet_Prefix `
-Subnet $subnetInternal -ResourceGroupName RG-MainSite `
-Location $resource_locaton_main
Step – 4: Add second subnet to virtual network
$vsubnet_dmz = "172.17.10.0/24"
#Fetch virtual network details
$vnet = Get-AzVirtualNetwork -Name $vnet_Name
#Add a subnet to existing vnet
Add-AzVirtualNetworkSubnetConfig -Name "v-subnet-dmz" -VirtualNetwork $vnet `
-AddressPrefix $vsubnet_dmz | Set-AzVirtualNetwork
Full Script:
#Connect to Azure
Connect-AzAccount
#Variable Declaration
$vnet_Name = "vnet-main"
$vnet_Prefix = "172.17.0.0/16"
$vsubnet_int = "172.17.1.0/24"
$vsubnet_dmz = "172.17.10.0/24"
$resource_locaton_main = 'Central US'
$resourceGroup_Name = "RG-MainSite"
#Create new Resource Group
New-AzResourceGroup -Name $resourceGroup_Name -Location $resource_locaton_main
#Create a Vnet and Subnet
$subnetInternal = New-AzVirtualNetworkSubnetConfig -Name "v-subnet-int" `
-AddressPrefix $vsubnet_int
New-AzVirtualNetwork -Name $vnet_Name -AddressPrefix $vnet_Prefix `
-Subnet $subnetInternal -ResourceGroupName RG-MainSite `
-Location $resource_locaton_main
#Fetch virtual network details
$vnet = Get-AzVirtualNetwork -Name $vnet_Name
#Add a subnet to existing vnet
Add-AzVirtualNetworkSubnetConfig -Name "v-subnet-dmz" -VirtualNetwork $vnet `
-AddressPrefix $vsubnet_dmz | Set-AzVirtualNetwork
Executing the above script will create a resource group, virtual network and 2 subnets.
Hope this is informative and thank you for reading the article.
Recent Comments