Azure, PowerShell : Removing an unused Public IP.

To continue my series on dealing with Azure VMs from PowerShell we will now look at how we remove a public IP that was previously, or even still is assigned to a VM.

First we need to understand a little of the basic network principles of Azure.

When you create a VM in Azure and assign it a public IP address, that VM does not actually have that public IP configured on any of its interfaces. Instead it has an IP from a private subnet configured and the public address you are given is simply NAT'ed onto that address by something called the AZ NAT Gateway.

When we delete a VM, Azure will not automatically delete any public IP's you have assigned to it as there may be occasions when we want to retain the IP and use it somewhere else.

In my previous post here we created an array that we used to define the parameters of our new VM (See bellow).

$vmParams = @{
  ResourceGroupName = 'Demo'
  Name = 'Demo1'
  Location = 'ukWest'
  ImageName = 'MicrosoftWindowsServer:WindowsServer:2022-Datacenter:latest'
  PublicIpAddressName = 'DemoPublicIp'
  Credential = $creds
  OpenPorts = 3389
  Size = 'Standard_B1ls'
}

New-AzVM @vmParams

Part of this array is the variable "PublicIpAddressName", In this example we used the value 'DemoPublicIp". This is where we define the public address we want to use for this machine, and the ports we want to NAT to it are just bellow that (OpenPorts.)

To reuse an IP you have used previously you could put the name of it here. You can see a list of public IP's you have here:

Or use this command:

Get-AzPublicIpAddress

If you want a new IP address just pick a name you haven't used before and it will automatically assign a new IP address for you.

Now lets get back to out scenario. You have delete a VM and you want to also delete the public IP address as you no longer need it.

The first thing we will need to do is to install the correct PS module.

Install-Module AZ.network

Then authenticate.

Connect-AzAccount

To get a list of the Public IP's we currently have do:

Get-AzPublicIpAddress

We cannot simply remove this IP address as it is currently associated with a AZ network interface on the AZ Gateway. If we try to use remove-AZPublicIpAddress we will get an error.

To view the AZ network interfaces we currently can use

Get-AzNetworkInterface

Now we can use the following to remove that interface

Remove-AzNetworkInterface -Name Demo1 -ResourceGroupName demo -Force

Once we have done this we can use the following to delete the IP

Remove-AzPublicIpAddress -Name DemoPublicIp -ResourceGroupName demo -Force

In both of these instances we need "-Force" otherwise we will be prompted with a confirmation popup. Not ideal in a script.