As all of us Azure cloud engineers know, removing a VM does not remove ancillary components such as disks, network interfaces, public ip addresses and network security groups. While these items are very low cost (with the exception of disks) in the grand scheme of things, they can make a difference in numbers. So, frequently grooming items which are NOT associated to other resources is key. Here are a few scripts to make this process easier:
Login-AzureRMAccount
# Remove unused disks from all subscriptions
Get-AzureRmSubscription | % {
Select-AzureRmSubscription -SubscriptionName $_.Name | Out-Null
"Subscription: $($_.Name)"
Get-AzureRmResourceGroup | % {
Get-AzureRmDisk -ResourceGroupName $_.ResourceGroupName | % {
if (!$_.OwnerId)
{
' --------------------'
" Disk Name: " + $_.Name
" Res Group: " + $_.ResourceGroupName
" Size in Gb: " + $_.DiskSizeGB
" Owner ID: " + $_.OwnerId
" Managed By: " + $_.ManagedBy
$_ | Remove-AzureRmDisk -Force
}
}
}
}
# Remove unused NIC's
Get-AzureRmSubscription | % {
Select-AzureRmSubscription -SubscriptionName $_.Name | Out-Null
"Subscription: $($_.Name)"
Get-AzureRmResourceGroup | % {
Get-AzureRmNetworkInterface -ResourceGroupName $_.ResourceGroupName | % {
if (!$_.VirtualMachine)
{
' --------------------'
" NIC Name: " + $_.Name
" VM: " + $_.VirtualMachine
$_ | Remove-AzureRmNetworkInterface -Force
}
}
}
}
# Remove public IP address
Get-AzureRmSubscription | % {
Select-AzureRmSubscription -SubscriptionName $_.Name | Out-Null
"Subscription: $($_.Name)"
Get-AzureRmResourceGroup | % {
" Res Group: $($_.ResourceGroupName)"
Get-AzureRmPublicIpAddress -ResourceGroupName $_.ResourceGroupName | % {
if (!$_.IpConfiguration)
{
" Name: $($_.Name)"
" Allocation: $($_.PublicIpAllocationMethod)"
" Ip Address: $($_.IpAddress)"
"-------------------------------"
$_ | Remove-AzureRmPublicIpAddress -Force
}
}
}
}
# Remove network security groups
Get-AzureRmSubscription | % {
Select-AzureRmSubscription -SubscriptionName $_.Name | Out-Null
"Subscription: $($_.Name)"
Get-AzureRmResourceGroup | % {
" Res Group: $($_.ResourceGroupName)"
Get-AzureRmNetworkSecurityGroup -ResourceGroupName $_.ResourceGroupName | % {
if ($_.NetworkInterfaces.Count -eq 0 -and $_.Subnets.Count -eq 0)
{
" Name: $($_.Name)"
$_ | Remove-AzureRmNetworkSecurityGroup
}
}
}
}
No comments:
Post a Comment