-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAzureUnusedResources.ps1
402 lines (332 loc) · 13.4 KB
/
AzureUnusedResources.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
Param(
[Parameter(Mandatory=$true)]
[ValidateSet('All','Storage','Network')]
[String[]] $Scope,
[Parameter(Mandatory=$true)]
[ValidateSet('Handled','Prompt','ServicePrincipal')]
[String[]] $AuthMode,
[String] $SPUser,
[String] $SPKey,
[String] $Tenant,
[Switch] $VerboseMode,
[Parameter(Mandatory=$true)]
[ValidateSet('AnalysisOnly','Production')]
[string[]] $Mode
)
# SCRIPT FUNCTIONS
function Log($message){
if($VerboseMode)
{
Write-Host $message -ForegroundColor Cyan
}
}
function GetVMProperties(){
# Get All VM Information
$AllVMS = Get-AzureRmVM
Log([String]::Format("Found {0} VMs", $AllVMS.Count))
foreach ($vm in $AllVMS) {
Log ([String]::Format("Getting information from VM {0}", $vm.Name))
$VMNames.Add($vm.name) > $null
# Boot Diagnostics
$diagnostics = $vm.DiagnosticsProfile.BootDiagnostics
If ($diagnostics.Enabled -eq $true){
$VMDiagnosticsStorageUrl.add($diagnostics.StorageUri) > $null
Log ([String]::Format("Diagnostics enabled for VM {0}. Diagnostics location is {1}", $vm.Name, $diagnostics.StorageUri))
}
# Disks
$storage = $VM.StorageProfile
$OSDisk = $storage.OsDisk
if($OSDisk.vhd -ne $null){
Log ([String]::Format("OS Disk is located in {0}", $OSDisk.vhd.uri))
$DiskURIList.Add($OSDisk.vhd.uri) > $null
}
else{
Log ([String]::Format("OS Managed Disk id is {0}", $vm.StorageProfile.OsDisk.ManagedDisk.Id))
$DiskURIList.Add($OSDisk.StorageProfile.OsDisk.ManagedDisk.Id) > $null
}
#$DataDisks = New-Object System.Collections.ArrayList
$DataDisks = $storage.DataDisks
foreach ($disk in $DataDisks) {
if($disk.vhd){
Log ([String]::Format("Data Disk is located in {0}", $disk.vhd.uri))
$DiskURIList.Add($disk.vhd.uri) > $null
}
}
# Network Interface Cards
$NICS = $vm.NetworkProfile.NetworkInterfaces
foreach ($nic in $NICS) {
$VMNICList.Add($nic.Id) > $null
$nicName = $nic.Id.substring($nic.id.LastIndexOf('/') + 1)
Log ([String]::Format("VM {0} contains NIC {1}", $vm.Name, $nicName))
}
}
}
function CollectStorageAccounts(){
}
function CollectManagedDisks(){
$ManagedDisks=Get-AzureRmDisk
Log ([String]::Format("Found {0} Managed Disks", $ManagedDisks.Count))
$diskCount = 0
foreach($disk in $ManagedDisks){
if($disk.OwnerId -eq $null){
$diskCount++
$ManagedDiskList.Add($disk.Id) > $null
}
}
Log ([String]::Format("Added {0} Managed Disks to List", $diskCount))
}
function CollectPIPs(){
$PublicIPs = Get-AzureRmPublicIpAddress
Log ([String]::Format("Found {0} Public IP Addresses", $PublicIPs.Count))
$pipCount = 0
foreach ($pip in $PublicIPs){
if($pip.IpConfiguration -eq $null){
$pipCount++
$PIPList.Add($pip.Id) > $null
}
else{
$pipConfigId = $pip.IpConfiguration.Id
if ($pipConfigId.split("/")[7] -ne 'virtualNetworkGateways'){
if($pipConfigId.Contains("/ipConfiguration")){
$nicId = $pipConfigId.Substring(0,$pipConfigId.IndexOf("/ipConfiguration"))
if(!$VMNICList.Contains($nicId)){
$pipCount++
$PIPList.Add($pip.Id) > $null
}
}
}
}
}
Log ([String]::Format("Added {0} Public IP Addresses to List", $pipCount))
}
function CollectNICs(){
$NICs=Get-AzureRmNetworkInterface
Log ([String]::Format("Found {0} NICs", $NICs.Count))
$nicCount = 0
foreach($nic in $NICs){
if($nic.VirtualMachine -eq $null){
$nicCount++
$NICList.Add($nic.Id) > $null
}
}
Log ([String]::Format("Added {0} NICs to List", $nicCount))
}
function CollectNSGs(){
$NSGs=Get-AzureRmNetworkSecurityGroup
Log ([String]::Format("Found {0} NSGs", $NSGs.Count))
$nsgCount = 0
foreach($nsg in $NSGs){
if(($nsg.NetworkInterfaces.Count -eq 0) -and ($nsg.Subnets.Count -eq 0)){
$nsgCount++
$NSGList.Add($nsg.Id) > $null
}
else{
if($nsg.Subnets.Count -eq 0){
$NICcheck = 0
foreach ($nic in $nsg.NetworkInterfaces){
if($NICList.contains($nic.Id)){
$NICcheck++
}
}
if($NICcheck -eq $nsg.NetworkInterfaces.Count){
$nsgCount++
$NSGList.Add($nsg.Id) > $null
}
}
}
}
Log ([String]::Format("Added {0} NSGs to List", $nsgCount))
}
function CollectSubnets(){
$VNETs=Get-AzureRmVirtualNetwork
Log ([String]::Format("Found {0} Virtual Networks", $VNETs.Count))
$subnetCount = 0
foreach($vnet in $VNETs){
foreach($subnet in $vnet.Subnets){
if($subnet.IPConfigurations.Count -eq 0){
if($subnet.ResourceNavigationLinks.Count -eq 0){
if($subnet.RouteTable -eq $null){
if($subnet.NetworkSecurityGroup -eq $null){
$subnetCount++
$SubnetList.Add($subnet.Id) > $null
}
}
}
}
}
}
Log ([String]::Format("Added {0} Subnets to List", $subnetCount))
}
function CollectVNETs(){
$VNETs=Get-AzureRmVirtualNetwork
Log ([String]::Format("Found {0} Virtual Networks", $VNETs.Count))
$vnetCount = 0
foreach($vnet in $VNETs){
if($vnet.VirtualNetworkPeerings.Count -eq 0){
$subnetCount = 0
foreach($subnet in $vnet.Subnets){
if($subnet.IPConfigurations.Count -eq 0){
if($subnet.ResourceNavigationLinks.Count -eq 0){
if($subnet.RouteTable -eq $null){
if($subnet.NetworkSecurityGroup -eq $null){
$subnetCount++
}
}
}
}
}
if($subnetCount -eq $vnet.Subnets.Count){
$vnetCount++
$VNETList.Add($vnet.Id) > $null
}
}
}
Log ([String]::Format("Added {0} VNETs to List", $vnetCount))
}
function Print($list){
foreach($item in $list){
$rname = $item.substring($item.LastIndexOf("/")+1, ($item.length - ($item.LastIndexOf("/")+1)))
Write-Output $rname
}
}
# VARIABLE DECLARATION
$SelectedSubscriptions = New-Object System.Collections.ArrayList
$VMNames = New-Object System.Collections.ArrayList
$VMDiagnosticsStorageUrl = New-Object System.Collections.ArrayList
$DiskURIList = New-Object System.Collections.ArrayList
$VMNICList = New-Object System.Collections.ArrayList
$ManagedDiskList = New-Object System.Collections.ArrayList
$PIPList = New-Object System.Collections.ArrayList
$NICList = New-Object System.Collections.ArrayList
$NSGList = New-Object System.Collections.ArrayList
$SubnetList = New-Object System.Collections.ArrayList
$VNETList = New-Object System.Collections.ArrayList
if($Mode -eq 'Production'){
Write-Warning "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
Write-Warning "! YOU ARE RUNNING IN PRODUCTION MODE. ANY RESOURCE DETECTED AS NOT BEING USED WILL BE DELETED. !"
Write-Warning "! IT IS A BEST PRACTICE TO RUN THIS SCRIPT IN ANALYSIS MODE FIRST !"
Write-Warning "! !"
Write-Warning "! PRESS [Y] TO CONTINUE !"
Write-Warning "! ...ANY OTHER KEY TO EXIT !"
Write-Warning "! !"
Write-Warning "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
$key = Read-Host
if ($key.toUpper() -ne "Y" -or $key -ne "y") {
Write-Host "SAFE QUIT" -ForegroundColor Green
exit
}
}
# MAIN SCRIPT
if($AuthMode -eq "Prompt"){
# Ask User for credentials
Log ("Asking user for credentials")
Add-AzureRmAccount
Log ("Successfuly authenticated")
}
elseif($AuthMode -eq "ServicePrincipal"){
# Validate Service Principal credentials
if($SPUser -eq $null -or $SPUser -eq "" `
-or $SPKey -eq $null -or $SPKey -eq "" `
-or $Tenant -eq $null -or $Tenant -eq ""){
Log("Values missing for Service Principal")
Write-Error "Service Principal Credentials are missing. When specifying '-ServicePrincipal' switch, UserName, Key and Tenant properties are mandatory. Exiting now."
exit
}
else{ # Authenticate with Service Principal Credentials
$pass = ConvertTo-SecureString $SPKey -AsPlainText -Force
$creds = New-Object -TypeName PSCredential -ArgumentList $SPUser, $pass
Log ([String]::Format("Authenticating with Service Principal",$SPUser))
Add-AzureRmAccount -Credential $creds -ServicePrincipal -TenantId $Tenant
Log ("Successfuly authenticated")
}
}
# Get List of Subscriptions
$AllSubscriptions = Get-AzureRmSubscription
Log([String]::Format("Found {0} Subscriptions", $AllSubscriptions.Count))
# If user is present ask which subscriptions should the script analyze
if(!$ServicePrincipal){
foreach ($subscription in $AllSubscriptions){
$title = $subscription.Name
$message = "Do you want the subscription " + $title + " to be analyzed?"
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
"Adds the subscription to the script."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
"Skips the subscription from scanning."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
switch ($result){
0 {
$SelectedSubscriptions.Add($subscription) > $null
Log ([String]::Format("Subscription {0} has been added", $subscription.Name))
}
1 {
Log ([String]::Format("Subscription {0} will be skipped", $subscription.Name))
}
}
}
}
else{
$SelectedSubscriptions = $AllSubscriptions
}
foreach ($subscription in $SelectedSubscriptions){
Log ([String]::Format("Analyzing {0}", $subscription.Name))
Select-AzureRmSubscription -SubscriptionId $subscription.Id
Log ("Subscription Selected.")
Log ("Starting VM Properties Collection")
GetVMProperties
Log ("Collected VM Properties")
Switch ($Scope) {
All {
Log ("Collecting information on Storage Accounts")
$StorageAccountsToProcess = CollectStorageAccounts
Log ("Collecting information on Managed Disks")
CollectManagedDisks
Log ("Collecting information on Networking")
CollectPIPs
CollectNICs
CollectNSGs
CollectSubnets
CollectVNETs
}
Storage {
Log ("Collecting information on Storage Accounts")
$StorageAccountsToProcess = CollectStorageAccounts
Log ("Collecting information on Managed Disks")
CollectManagedDisks
}
Network {
Log ("Collecting information on Networking")
CollectPIPs
CollectNICs
CollectNSGs
CollectSubnets
CollectVNETs
}
Default {
}
}
}
if($Mode -eq 'Production'){
# Removes resources identified as unused
}
elseif ($Mode -eq 'AnalysisOnly'){
# Prints resources identified as unused to the screen
Write-Host "******************************************************************" -ForegroundColor Yellow
Write-Host "* ANALYSIS SUMMARY *" -ForegroundColor Yellow
Write-Host "******************************************************************" -ForegroundColor Yellow
Write-Host "* The following items have been identified as not being used *" -ForegroundColor Yellow
Write-Host "* and they can be removed. *" -ForegroundColor Yellow
Write-Host "******************************************************************" -ForegroundColor Yellow
Write-Host "MANAGED DISKS:" -ForegroundColor Yellow
Print -list $ManagedDiskList
Write-Host "PUBLIC IPS:" -ForegroundColor Yellow
Print -list $PIPList
Write-Host "NETWORK INTERFACES:" -ForegroundColor Yellow
Print -list $NICList
Write-Host "NETWORK SECURITY GROUPS:" -ForegroundColor Yellow
Print -list $NSGList
Write-Host "SUBNETS:" -ForegroundColor Yellow
Print -list $SubnetList
Write-Host "VNETS:" -ForegroundColor Yellow
Print -list $VNETList
}