Sunday, September 6, 2020

Azure/PowerShell: Finding and Removing Orphaned Network Interfaces

When an Azure virtual machine is deleted via the portal ( any network interfaces associated with the VM are not deleted. This can lead to the pool of IP addresses associated with a subnet to be exhausted and no new VMs can be created as there are no IP addresses to assign to the new VMs.

The Get-AzNetworkInterface cmdlet returns all network instances for an Azure subscription and the Remove-AzNetworkInterface cmdlet removes a specific network interface. The following code uses Get-AzNetworkInterface in conjunction with Where-Object to get all orphaned network interfaces. Each network interface is represented by an instance of type PSNetworkInterface

[string] $subID = 'put subscription ID here'

Select-AzureRmSubscription `
 -Subscriptionid $SubID | Out-Null

[Microsoft.Azure.Commands.Network.Models.PSNetworkInterface []] ` 
 $nics =
   Get-AzNetworkInterface |
   Where-Object {
     ($_.VirtualMachine -eq $null) -And
     (($_.PrivateEndpointText -eq $null) -Or
      ($_.PrivateEndpointText -eq 'null'))}

foreach ($nic in $nics)
     "Removing Orphaned NIC $($nic.Name) $($nic.resourcegroupname)"
 Remove-AzNetworkInterface `
   -Name $nic.Name `
   -ResourceGroupName $nic.resourcegroupname `
   -Force }

The Get-AzNetworkInterface | Where-Object code returns only network interfaces:

  • Not associated with virtual machines
  • Not associated with private endpoints 

This script snippet detects if a network interface is not associated with a virtual machine:

($_.VirtualMachine -eq $null)

This script snippet detects if a network interface is not associated with a private endpoint:

     (($_.PrivateEndpointText -eq $null) -Or 
      ($_.PrivateEndpointText -eq 'null'))}

Not being associated with a virtual machine appears to identify a network interface as orphaned having formally been assigned to a now deleted VM. There are network interfaces that were never associated with a virtual machine such as a network interface associated with a private endpoint. This is why there is an additional check to insure the PSNetworkInterface.PrivateEndpointText property is not assigned. Private endpoints are ancillary germane to detecting/removing orphaned network interfaces. More information on private endpoints can be found at What is Azure Private Endpoint?.

No comments :

Post a Comment