Azure PowerShell: Add port forwarding load balancer to existing VM

In this blog post, I’ll share some Azure PowerShell code that I often use to attach a load balancer to existing Azure VMs (Virtual Machines). The code is both useful when you want to split the load to more nodes, but also to be able to create NAT rules and port forwarding for your VMs.

# authentication using service principal (appid+secret)
$tenantid = '<tenant-id>';
$appid = '<app-id>';
$secret = ConvertTo-SecureString '<app-secret>' -AsPlainText -Force;
$cred = New-Object System.Management.Automation.PSCredential ($appid, $secret);
Login-AzAccount -ServicePrincipal -TenantId $tenantid -Credential $cred
# if login does not succeed with service principal then prompt for login
if ([string]::IsNullOrEmpty($(Get-AzureRmContext).Account)) {Login-AzureRmAccount}
# name of the VM to which you want to attach your load balancer
$vmname = 'my-vm0';
# name of resource group containing your VM
$rg = 'my-vm-rg';
# name of your new load balancer
$lbname = 'my-vm-lb0';
# name of the NIC attached to your VM
# this will later be used for binding the VM and load balancer together
$nicname = 'my-vm0120';
# public ip address exposed by the load balancer through a frontend ip configuraion
$pip = New-AzureRmPublicIpAddress -Name "$rg-pip0" -ResourceGroupName $rg -Location 'West Europe' -Sku Basic -AllocationMethod Dynamic;
$frontconfig = New-AzureRmLoadBalancerFrontendIpConfig -Name lb0-frontconfig -PublicIpAddress $pip;
# ip address configuration for backend pool. later the NIC for the VM will bind to this configuration
$backendpool = New-AzureRmLoadBalancerBackendAddressPoolConfig -Name lb0-backpoolconfig
# the inbound NAT rule tells the load balancer to forward port 443 to 3389
$inboundnatrule = New-AzureRmLoadBalancerInboundNatRuleConfig -Name lb0-inboundnatrule -FrontendIpConfiguration $frontconfig -Protocol Tcp -FrontendPort 443 -BackendPort 3389;
# the actual load balancer is created. the basic SKU is fine when doing port forwarding like this.
$lb = New-AzureRmLoadBalancer -ResourceGroupName $rg -Location 'West Europe' -Name $lbname -Sku Basic -FrontendIpConfiguration $frontconfig -InboundNatRule $inboundnatrule -BackendAddressPool $backendpool
# once the load balancer is created, we need to associate the NIC of the VM
# to both the backend address pool and the inbound NAT rule
$nic = Get-AzureRmNetworkInterface -ResourceGroupName $rg -Name $nicname
$nic | Set-AzureRmNetworkInterface

Photo by Jeff Pang