DEV Community

iapilgrim
iapilgrim

Posted on

Mastering Azure VNet Peering with PowerShell Automation

In Azure, Virtual Networks (VNets) are isolated by default. To allow resources in different departments—like Production and Development—to communicate securely over the Microsoft backbone, we use VNet Peering.

The Scenario

We are building two distinct environments:

  1. Production VNet: 10.1.0.0/16
  2. Development VNet: 10.2.0.0/16

Our goal is to connect them so that a VM in Production can reach a VM in Development using private IP addresses.


1. The Core Concepts

  • VNet Peering: A low-latency, high-bandwidth connection. Traffic is private and never touches the public internet.
  • Transitivity: Peering is not transitive. If A is peered with B, and B is peered with C, A cannot talk to C unless you peer them directly.
  • NSGs: Network Security Groups act as a firewall. Even if networks are peered, the NSG must allow the specific traffic (like ICMP/Ping).

2. The Complete Automation Script

This script handles the entire lifecycle: Resource Group creation, Networking, Security, VM Deployment, and Peering initialization.

# =================================================================
# AZURE VNET PEERING LAB: FULL AUTOMATION SCRIPT
# =================================================================

# 1. Configuration
$rgName   = "Lab-Network-RG"
$location = "eastus2"
$adminUser = "azureuser"
$adminPass = ConvertTo-SecureString "P@ssw0rd123456!" -AsPlainText -Force
$myCred    = New-Object System.Management.Automation.PSCredential($adminUser, $adminPass)

# 2. Create the Resource Group
Write-Host "Creating Resource Group..." -ForegroundColor Cyan
New-AzResourceGroup -Name $rgName -Location $location

# 3. Create Network Security Group (Allow Ping/ICMP)
Write-Host "Configuring Security Rules..." -ForegroundColor Cyan
$icmpRule = New-AzNetworkSecurityRuleConfig -Name "Allow-Ping" -Access Allow -Protocol Icmp `
    -Direction Inbound -Priority 100 -SourceAddressPrefix "10.0.0.0/8" `
    -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange *

$nsg = New-AzNetworkSecurityGroup -ResourceGroupName $rgName -Location $location `
    -Name "Lab-NSG" -SecurityRules $icmpRule

# 4. Create Virtual Networks
Write-Host "Building Production and Development VNets..." -ForegroundColor Cyan
$subProd = New-AzVirtualNetworkSubnetConfig -Name "Prod-Subnet" -AddressPrefix "10.1.1.0/24" -NetworkSecurityGroup $nsg
$vnetProd = New-AzVirtualNetwork -ResourceGroupName $rgName -Location $location -Name "VNet-Prod" `
    -AddressPrefix "10.1.0.0/16" -Subnet $subProd

$subDev = New-AzVirtualNetworkSubnetConfig -Name "Dev-Subnet" -AddressPrefix "10.2.1.0/24" -NetworkSecurityGroup $nsg
$vnetDev = New-AzVirtualNetwork -ResourceGroupName $rgName -Location $location -Name "VNet-Dev" `
    -AddressPrefix "10.2.0.0/16" -Subnet $subDev

# 5. Deploy Test VMs (Linux/Ubuntu)
Write-Host "Deploying Virtual Machines (approx 2 mins)..." -ForegroundColor Green
$vmParams = @{
    ResourceGroupName = $rgName
    Location          = $location
    Size              = "Standard_B2ts_v2"
    Credential        = $myCred
    Image             = "Canonical:0001-com-ubuntu-server-jammy:22_04-lts:latest"
    OpenPorts         = 22
}

New-AzVm @vmParams -Name "Prod-VM" -VirtualNetworkName "VNet-Prod" -SubnetName "Prod-Subnet" -PublicIpAddressName "Prod-IP"
New-AzVm @vmParams -Name "Dev-VM" -VirtualNetworkName "VNet-Dev" -SubnetName "Dev-Subnet" -PublicIpAddressName "Dev-IP"

# 6. Establish Bidirectional VNet Peering
Write-Host "Initiating VNet Peering..." -ForegroundColor Yellow
Add-AzVirtualNetworkPeering -Name "Prod-to-Dev" -VirtualNetwork $vnetProd -RemoteVirtualNetworkId $vnetDev.Id
Add-AzVirtualNetworkPeering -Name "Dev-to-Prod" -VirtualNetwork $vnetDev -RemoteVirtualNetworkId $vnetProd.Id

Write-Host "Deployment Complete!" -ForegroundColor Green

Enter fullscreen mode Exit fullscreen mode

3. Automated Verification

Once deployed, you don't need to manually log into a console. You can use the Azure RunCommand to execute a ping test from within the Production VM to the Development VM.

# Fetch Dev-VM Private IP
$targetIP = (Get-AzNetworkInterface -ResourceGroupName $rgName | Where-Object Name -Like "*Dev-VM*" | Select-Object -ExpandProperty IpConfigurations).PrivateIpAddress

# Run the test
$result = Invoke-AzVMRunCommand `
    -ResourceGroupName $rgName `
    -VMName "Prod-VM" `
    -CommandId "RunShellScript" `
    -ScriptString "ping -c 4 $targetIP"

# Show results
$result.Value.Message

Enter fullscreen mode Exit fullscreen mode

4. Summary for the Lab Report

  • VNet Peering is the standard for connecting Azure workloads because it uses the high-speed backbone.
  • The Serial Console is an invaluable tool for "out-of-band" management when standard SSH/RDP fails.
  • Automation via `Invoke-AzVMRunCommand` allows for rapid validation of networking changes without needing to manage SSH keys or public access.

Situations where Peering does NOT apply:

  1. Overlapping IPs: Use a VPN Gateway with NAT.
  2. Legacy Global Limits: Though rare now, very large scale deployments might hit peering limits per VNet (currently 500).
  3. On-Premises: Requires a VPN or ExpressRoute.

Top comments (0)