Skip to content

Instantly share code, notes, and snippets.

@rasmusgude
Created June 10, 2018 19:12
Show Gist options
  • Save rasmusgude/830911d9ea6f77adf071dc70482bf8bf to your computer and use it in GitHub Desktop.
Save rasmusgude/830911d9ea6f77adf071dc70482bf8bf to your computer and use it in GitHub Desktop.
# 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.IpConfigurations[0].LoadBalancerBackendAddressPools.Add($backendpool)
$nic.IpConfigurations[0].LoadBalancerInboundNatRules.Add($inboundnatrule)
$nic | Set-AzureRmNetworkInterface
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment