skip to Main Content

How to list and remove unused (orphanip) public ip address "such as search if the ip is not associated to any Vm or Networkinterface card find and then delete" in azure using powershell azure automation runbook.
Getting this error "Method ‘get_SerializationSettings’ in type ‘Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient’ from assembly ‘Microsoft.Azure.Commands.ResourceManager.Common, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ does not have an implementation."
Run Login-AzureRmAccount to login.

 [CmdletBinding(SupportsShouldProcess=$true,
   ConfirmImpact="High")]
    Param
    (
        # Specifies the name of the resource group from which Public IP Addresses are to be retrieved.
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$ResourceGroup,
        # Only lists Azure Network Interfaces that are not linked to an existing Azure Virtual Machine
        [switch]$ListOnly
    )
    Begin
    {
        If (AzureRmResourceGroup -Name $ResourceGroup -ErrorAction SilentlyContinue )
        {        
            $az_publicipaddress = Get-AzureRmPublicIpAddress -ResourceGroupName $ResourceGroup
            $RemAzPublicIP = $az_publicipaddress |  Where-Object {$_.IpConfiguration -eq $null}
        }
        Else
        {
            Write-Error "Provided resource group does not exist: $ResourceGroup"
            Throw
        }
    }
    Process
    {
        $removed = @()
        If ($PSBoundParameters.ContainsKey("ListOnly"))
        {
            $RemAzPublicIP | Select-Object Name,ResourceGuid
        }
        Else
        {
            ForEach($pi in $RemAzPublicIP)
            {
                if ($pscmdlet.ShouldProcess("Deleting NetworkInterface $($pi.Name)"))
                {
                   Write-Output "Removing Public IP Address without Virtual Machine association: $($pi.Name)"
                   Remove-AzureRmPublicIpAddress -Name "$($pi.name)" -ResourceGroupName $ResourceGroup 
                   $object = New-Object -TypeName PSObject
                   $object | Add-Member -MemberType NoteProperty -Name Name -Value $($pi.Name)
                   $object | Add-Member -MemberType NoteProperty -Name ResourceGuid -Value $($pi.ResourceGuid)
                   $removed += $object
                }
            }
        }
    }
    End
    {
        # List the removed objects
        $removed 
    }

2

Answers


  1. You can utilise Get-AzNetworkInterface to return all NICs within your current context.

    You would have to filter the results to see which were not attached to a virtual machine.

    # This will return NICs which aren't associated to a VM
    $orphanedNics = Get-AzNetworkInterface | Where-Object VirtualMachine -eq $null
    

    If you have a lot of resources to check then you could use Search-AzGraph from the Az.ResourceGraph module to perform the search.

    $query = '
    Resources
    | where type has "microsoft.network/networkinterfaces"
    | where properties !has "virtualmachine"'
    
    $orphanedNics = Search-AzGraph -Query $query
    

    Once you have those results and validated it’s correct you can then use Remove-AzNetworkInterface to delete.

    Login or Signup to reply.
  2. Microsoft has dedicated document to handle it – https://learn.microsoft.com/en-us/previous-versions/azure/virtual-machines/linux/find-unattached-nics

    Note that Microsoft doesn’t pay attention to NICs attached to private endpoints that can part of other resource, they only talking about "unattached network interface cards (NICs) for Azure VMs".

    Therefore I added reference to ‘privateEndpoint’ as well

    –query ‘[?virtualMachine==null && privateEndpoint==null].[id]’

    You can add it to Microsoft code and make the deletion automatic, I decided to do it manual and don’t take risks, so used the following to list those nics:

    sub=<subscription_id> ;
    az network nic list --subscription $sub --query '[?virtualMachine==`null` && privateEndpoint==`null`].[id]'
    

    or for better output view

    sub=<subscription_id> ;
    unattachedNicsIds=$(az network nic list --subscription $sub --query '[?virtualMachine==`null` && privateEndpoint==`null`].[id]' -o tsv) ; for id in ${unattachedNicsIds[@]}; do echo $id | awk -FMicrosoft.Network/networkInterfaces/ '{print $2}'; done
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search