NSX-T: Find and Delete Orphaned Ports
Summary:
Basically had a bunch of orphaned ports (65000+), don't know why or how it happened (hypothetically NTP related), but needed to clean them up. Doing it via UI was obviously not an option as it would only return 50 ports per page at a time. Oh and it wouldn't refresh after every delete.
Details:
I'm saying 'orphaned', but in reality I'm only keying off the idea that the port is reporting "Operationally Down". This could simply be a powered off VM, but there is little harm in deleting these type of ports as they will simply be recreated if that VM were to be powered up.
This may not apply in all situations, so use this with caution.
Powershell Example(s):
$NSXMgr = Read-Host "Enter NSX Manager IP or DNS name:" | |
$Creds = Get-Credential -Message "Enter NSX username and password" | |
$PortData = @() | |
$Segments = Invoke-RestMethod -Authentication Basic -Credential $creds -Method Get -Uri "https://$NSXMgr/policy/api/v1/infra/segments/" -SkipCertificateCheck:$true | |
Foreach ($Segment in $Segments.results){ | |
$Ports = Invoke-RestMethod -Authentication Basic -Credential $creds -Method Get -Uri "https://$NSXMgr/policy/api/v1/infra/segments/$($Segment.id)/ports/" -SkipCertificateCheck:$true | |
$PortData += $Ports.results | |
While (!([string]::IsNullOrEmpty($Ports.cursor))){ | |
$Ports = Invoke-RestMethod -Authentication Basic -Credential $creds -Method Get -Uri "https://$NSXMgr/policy/api/v1/$($Segment.id)/ports?cursor=$($ports.cursor)" -SkipCertificateCheck:$true | |
$PortData += $Ports.results | |
} | |
} | |
Start-Transcript #Outputs gather data just in case it's needed. | |
$PortData | |
$TranscriptLocation = Stop-Transcript #Data saved in text file. | |
Write-Host "Ctrl-C here to stop and review data captured in transcript file. Otherwise, script will continue to delete 'Operationally DOWN' ports." | |
Pause -Message "$($TranscriptLocation)" | |
Start-Transcript | |
# Uses Manager API to check operational status of port, then delete if that status returns as "DOWN" | |
# Policy API may be required in future revisions, but not deprecated as of 4.0 | |
$DeletedPorts = @() | |
Foreach ($port in $PortData){ | |
$portopinfo = Invoke-RestMethod -Authentication Basic -Credential $creds -Method Get -Uri "https://$NSXMgr/api/v1/logical-ports/$($port.id)/status" -SkipCertificateCheck:$true | |
If ($portopinfo.status -eq "DOWN"){ | |
Invoke-RestMethod -Authentication Basic -Credential $creds -Method DELETE -Uri "https://$NSXMgr/api/v1/logical-ports/$($port.id)?detach=true" -SkipCertificateCheck:$true | |
Write-Host "Deleted Port id: $($port.id) attached to logical switch id: $($port.logical_switch_id)." | |
$DeletedPorts += $Port | |
} | |
} | |
Stop-Transcript | |
Start-Transcript #Output Deleted Ports Data here | |
$DeletedPorts | |
Stop-Transcript |
References:
https://www.virten.net/2021/03/error-when-connecting-virtual-machine-to-nsx-t-segments/
Comments