Create Azure VNET peering using PowerShell

Today I want to show you how in easy way create Azure VNET peering using PowerShell.

What is VNET peering?

VNET peering allows to connect virtual networks to each other. When virtual networks are peered, all resourcses inside those networks are able to communicate the same way and with the same bandwidth if the resources will be created in the same virtual network.

Script:
function Create-AzureNetworkPeering {
 
    Param(
        [Parameter(Position = 0, Mandatory = $true, HelpMessage = "Vnet1 name", ValueFromPipeline = $false)] 
        $Vnet1,
        [Parameter(Position = 1, Mandatory = $true, HelpMessage = "Resource group name for vnet1", ValueFromPipeline = $false)] 
        $Vnet1ResourceGroup,
        [Parameter(Position = 2, Mandatory = $true, HelpMessage = "Vnet2 name", ValueFromPipeline = $false)] 
        $Vnet2,
        [Parameter(Position = 3, Mandatory = $true, HelpMessage = "Resource group name for vnet2", ValueFromPipeline = $false)] 
        $Vnet2ResourceGroup

    )
                
    If (!(Get-AzureRmContext)) {
        Write-Host "Please login to your Azure account"
        Login-AzureRmAccount
    }

    Try {
        $VirtualNetwork1 = Get-AzureRmVirtualNetwork -Name $Vnet1 -ResourceGroupName $Vnet1ResourceGroup
    }
    Catch {
        Write-Error "VNET $Vnet1 can not be found!"
        break
    }

    Try {
        $VirtualNetwork2 = Get-AzureRmVirtualNetwork -Name $Vnet2 -ResourceGroupName $Vnet2ResourceGroup
    }
    Catch {
        Write-Error "VNET $Vnet2 can not be found!"
        break
    }
 
    Add-AzureRmVirtualNetworkPeering -Name $vnet1-$vnet2 -VirtualNetwork $VirtualNetwork1 -RemoteVirtualNetworkId $VirtualNetwork2.Id | Out-Null
    Add-AzureRmVirtualNetworkPeering -Name $vnet2-$vnet1 -VirtualNetwork $VirtualNetwork2 -RemoteVirtualNetworkId $VirtualNetwork1.Id | Out-Null

    $PeeringStateVNET1 = (Get-AzureRmVirtualNetworkPeering -ResourceGroupName $Vnet1ResourceGroup -VirtualNetworkName $Vnet1 | Select PeeringState).PeeringState
    $PeeringStateVNET2 = (Get-AzureRmVirtualNetworkPeering -ResourceGroupName $Vnet2ResourceGroup -VirtualNetworkName $Vnet2 | Select PeeringState).PeeringState

    Write-Host "Peering status for $VNET1 is $PeeringStateVNET1"
    Write-Host "Peering status for $VNET2 is $PeeringStateVNET2"
}
Example of usage:
Create-AzureNetworkPeering -Vnet1 vnet1 -Vnet1ResourceGroup vnet1rg -Vnet2 vnet2 -Vnet2ResourceGroup vnet2rg

I hope it will be usefull for some of you 😉
Enjoy!

Leave a Reply

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