Associate Azure Public IP to an existing network interface using Powershell

Associate Azure Public IP to an existing network interface using Powershell

Today I needed to associate a public IP address to an existing Azure virtual machine. The Microsoft Docs website has an article that describes how to do it. But somehow the Powershell example didn't work.

In this short post I will provide you with a Powershell snippet that will actually work.

The Powershell example

The example below creates a public IP address in Azure and associates it to an existing Network Interface.

  • You can either use the Azure Cloud Shell or use a local installation of Powershell to execute the code snippet. If you are using Powershell locally, make sure you have the Azure Powershell module installed.
  • If you have multiple subscriptions, use the Select-AzSubscription command first to select the right subscription.
1    $pip = New-AzPublicIpAddress -Name 'MyPublicIpName' -ResourceGroupName 'MyResourceGroupName' -Sku 'Basic' -AllocationMethod 'Dynamic' -Location 'West Europe'
2    $vnet = Get-AzVirtualNetwork -Name 'MyVnetName' -ResourceGroupName 'MyResourceGroupName'
3    $subnet = Get-AzVirtualNetworkSubnetConfig -Name 'MySubnetName' -VirtualNetwork $vnet
4    $nic = Get-AzNetworkInterface -Name 'MyNicName' -ResourceGroupName 'MyResourceGroupName'
5    $ipconfig = New-AzNetworkInterfaceIpConfig -Name 'MyIpConfigName' -Subnet $subnet -PublicIpAddress $pip
6    $nic | Add-AzNetworkInterfaceIpConfig -Name $ipconfigName -Subnet $subnet -PublicIpAddress $pip
7    $nic | Set-AzNetworkInterface

In the example I create a public IP of Sku "Basic", allocation method "Dynamic" and in region "West Europe". You might need to change these values to your specific needs. Consult the docs on the New-AzPublicIpAddress cmdlet here.

Conclusion

If Powershell is your tool of choice, and you need add a public IP address to an existing network interface, this code snippet will work for you.