-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMarkAndDeleteUnusedResources.ps1
More file actions
2336 lines (2213 loc) · 124 KB
/
MarkAndDeleteUnusedResources.ps1
File metadata and controls
2336 lines (2213 loc) · 124 KB
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
This script checks each Azure resource (group) across all subscriptions and
eventually tags it as subject for deletion or (in some cases) deletes it
automatically (after confirmation, configurable). Based on the tag's value
suspect resources can be confirmed or rejected as subject for deletion and
will be considered accordingly in subsequent runs.
.DESCRIPTION
___
__ ███████╗ █████╗ ██╗ ██╗███████╗
██╔════╝██╔══██╗██║ ██║██╔════╝
███████╗███████║██║ ██║█████╗
╚════██║██╔══██║╚██╗ ██╔╝██╔══╝
███████║██║ ██║ ╚████╔╝ ███████╗
╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚══════╝
███╗ ███╗ ██████╗ ███╗ ██╗███████╗██╗ ██╗
████╗ ████║██╔═══██╗████╗ ██║██╔════╝╚██╗ ██╔╝
██╔████╔██║██║ ██║██╔██╗ ██║█████╗ ╚████╔╝
██║╚██╔╝██║██║ ██║██║╚██╗██║██╔══╝ ╚██╔╝ __
██║ ╚═╝ ██║╚██████╔╝██║ ╚████║███████╗ ██║ ____
╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ___
and energy, and clean-up...
This script was primarily written to clean-up large Azure environments and
potentially save money along the way. It was inspired by the project
'itoleck/AzureSaveMoney'.
This script was deliberately written in a single file to ensure ease of use.
The log output is written to the host with colors to improve human readability.
The default values for some parameters can be specified in a config file named
'Defaults.json'.
The script implements function hooks named for each supported resource
type/kind. Function hooks determine for a specific resource which action shall
be taken. The naming convention for hooks is
"Test-ResourceActionHook-<resourceType>[-<resourceKind>]". New hooks can easily
be added by implementing a new function and will be discovered and called
automatically. New hooks should be inserted after the marker [ADD NEW HOOKS
HERE].
There are multiple tags which are set when a resource is marked as subject for
deletion (tag names are configurable):
- "SubjectForDeletion",
- "SubjectForDeletion-FindingDate",
- "SubjectForDeletion-Reason" and
- "SubjectForDeletion-Hint" (optional).
The "SubjectForDeletion" tag has one of the following values after the script
ran and the tag was created:
- "suspected": resource marked as subject for deletion
- "suspectedSubResources": at least one sub resource is subject for deletion
As long as the tag `SubjectForDeletion` has a value starting with
`suspected...` the resource is reevaluated in every run and the tag value is
updated (overwritten). You can update the tag value to one of the following
values in order to influence the script behavior in subsequent runs (see below).
The following example process is suggested to for large organizations:
1. RUN script regularly
2. ALERT `suspected` or `suspectedSubResources` resources to owners
3. MANUAL RESOLUTION by owners by reviewing and changing the tag value of
`SubjectForDeletion` to one of the following values (case-sensitive!):
- `rejected`: Resource is needed and shall NOT be deleted (this status will
not be overwritten in subsequent runs for 6 months after
`SubjectForDeletion-FindingDate`).
- `confirmed`: Resource shall be deleted (will be automatically deleted in
the next run).
4. AUTO-DELETION/REEVALUATION: Subsequent script runs will check all resources
again with the following special handling for status:
- `confirmed`: resource will be deleted.
- `suspected`: if `SubjectForDeletion-FindingDate` is older that 30 days
(e.g. resource was not reviewed in time), the resource will be
automatically deleted.
Project Link: https://github.com/thgossler/AzSaveMoney
Copyright (c) 2022-2024 Thomas Gossler
License: MIT
Tags: Azure, ResourceManagement, Automation, Cleanup, CostOptimization, ClimateProtection, PowerShell, UnusedResources, Tagging, Deletion, Scripting, Cloud, Infrastructure, ResourceTracking, Efficiency, Governance, FinOps
.PARAMETER TenantId
The ID of the Microsoft Entra ID tenant. Can be set in defaults config file.
.PARAMETER AzEnvironment
The Azure environment name (for options call "(Get-AzEnvironment).Name"). Can be set in defaults config file.
.PARAMETER SubscriptionIdsToProcess
The list of Azure subscription IDs to process. If empty all subscriptions will be processed. Can be set in defaults config file.
.PARAMETER DontDeleteEmptyResourceGroups
Prevents that empty resource groups are processed.
.PARAMETER AlwaysOnlyMarkForDeletion
Prevent any automatic deletions, only tag as subject for deletion.
.PARAMETER TryMakingUserContributorTemporarily
Add a Contributor role assignment temporarily for each subscription.
.PARAMETER CentralAuditLogAnalyticsWorkspaceId
Also use this LogAnalytics workspace for querying LogAnalytics diagnostic 'Audit' logs.
.PARAMETER CheckForUnusedResourceGroups
Checks for old resources groups with no deployments for a long time and no write/action activities in last 90 days.
.PARAMETER MinimumResourceAgeInDaysForChecking
Minimum number of days resources must exist to be considered (default: 4, lower or equal 0 will always check). Can be set in defaults config file.
.PARAMETER DisableTimeoutForDeleteConfirmationPrompt
Disable the timeout for all delete confirmation prompts (wait forever)
.PARAMETER DeleteSuspectedResourcesAndGroupsAfterDays
Delete resources and groups which have been and are still marked 'suspected' for longer than the defined period. (default: -1, i.e. don't delete). Can be set in defaults config file.
.PARAMETER EnableRegularResetOfRejectedState
Specifies that a 'rejected' status shall be reset to 'suspected' after the specified period of time to avoid that unused resources are remaining undetected forever.
.PARAMETER ResetOfRejectedStatePeriodInDays
Specifies the period of time in days after which a 'rejected' status is reset to 'suspected'. (default: 6 months)
.PARAMETER DocumentationUrl
An optional URL pointing to documentation about the context-specific use of this script. Can be set in defaults config file.
.PARAMETER UseDeviceAuthentication
Use device authentication.
.PARAMETER AutomationAccountResourceId
Use the system-assigned managed identity of this Azure Automation account for authentication (full resource ID).
.PARAMETER ServicePrincipalCredential
Use these service principal credentials for authentication.
.PARAMETER EnforceStdout
Redirect all displayed text (Write-HostOrOutput) to standard output.
.INPUTS
Azure resources/groups across all (or specified) subscriptions.
.OUTPUTS
Resource/group tags "SubjectForDeletion", "SubjectForDeletion-Reason",
"SubjectForDeletion-FindingDate", "SubjectForDeletion-Hint", deleted empty
resource groups eventually.
.NOTES
Warnings are suppressed by $WarningPreference='SilentlyContinue'.
#>
#Requires -Version 7
#Requires -Modules Az.Accounts
#Requires -Modules Az.Batch
#Requires -Modules Az.DataProtection
#Requires -Modules Az.Monitor
#Requires -Modules Az.ResourceGraph
#Requires -Modules Az.Resources
#Requires -Modules Az.ServiceBus
#Requires -Modules PowerShellGet
################################################################################
# Configuration Settings
################################################################################
[CmdletBinding(SupportsShouldProcess)]
param (
# The ID of the Microsoft Entra ID AD tenant. Can be set in defaults config file.
[string]$TenantId = "",
# Deprecated. Use TenantId instead. Will be removed in future versions.
[string]$DirectoryId = $TenantId,
# The Azure environment name (for options call "(Get-AzEnvironment).Name").
# Can be set in defaults config file.
[string]$AzEnvironment,
# The list of Azure subscription IDs to process. If empty all subscriptions
# will be processed. Can be set in defaults config file.
[string[]]$SubscriptionIdsToProcess = @(),
# Prevents that empty resource groups are processed.
[switch]$DontDeleteEmptyResourceGroups = $false,
# Prevent any automatic deletions, only tag as subject for deletion.
[switch]$AlwaysOnlyMarkForDeletion = $false,
# Add a Contributor role assignment temporarily for each subscription.
[switch]$TryMakingUserContributorTemporarily = $false,
# Also use this LogAnalytics workspace for querying LogAnalytics diagnostic
# 'Audit' logs.
[string]$CentralAuditLogAnalyticsWorkspaceId = $null,
# Checks for old resources groups with no deployments for a long time and
# no write/action activities in last 90 days.
[switch]$CheckForUnusedResourceGroups = $false,
# Minimum number of days resources must exist to be considered (default: 4,
# lower or equal 0 will always check). Can be set in defaults config file.
[int]$MinimumResourceAgeInDaysForChecking = 1,
# Disable the timeout for all delete confirmation prompts (wait forever)
[switch]$DisableTimeoutForDeleteConfirmationPrompt = $false,
# Delete resources and groups which have been and are still marked
# 'suspected' for longer than the defined period. (default: -1, i.e. don't
# delete). Can be set in defaults config file.
[int]$DeleteSuspectedResourcesAndGroupsAfterDays = -1,
# Specifies that a 'rejected' status shall be reset to 'suspected' after
# the specified period of time to avoid that unused resources are remaining
# undetected forever.
[switch]$EnableRegularResetOfRejectedState = $false,
# Specifies the duration in days after which a 'rejected' status is reset
# to 'suspected'. (default: 6 months)
[int]$ResetOfRejectedStatePeriodInDays = -1,
# An optional URL pointing to documentation about the context-specific
# use of this script. Can be set in defaults config file.
[string]$DocumentationUrl = $null,
# Use device authentication.
[switch]$UseDeviceAuthentication,
# Use the system-assigned managed identity of this Azure Automation account
# for authentication (full resource ID).
[string]$AutomationAccountResourceId = $null,
# Use these service principal credentials for authentication.
[PSCredential]$ServicePrincipalCredential = $null,
# Redirect all displayed text (Write-HostOrOutput) to standard output.
[switch]$EnforceStdout
)
$ErrorActionPreference = "Stop"
function Write-HostOrOutput {
param (
[Parameter(Mandatory = $false, Position = 0)]
[string]$Message = "",
[Parameter(Mandatory = $false, Position = 1)]
[System.ConsoleColor]$ForegroundColor = [System.ConsoleColor]::Gray,
[Parameter(Mandatory = $false, Position = 2)]
[System.ConsoleColor]$BackgroundColor = [System.ConsoleColor]::Black,
[Parameter(Mandatory = $false, Position = 3)]
[switch]$NoNewline = $false
)
if ($EnforceStdout.IsPresent) {
Write-Output $Message
}
else {
Write-Host $Message -ForegroundColor $ForegroundColor -BackgroundColor $BackgroundColor -NoNewline:$NoNewline
}
}
# Get configured defaults from config file
$defaultsConfig = (Test-Path -Path $PSScriptRoot/Defaults.json -PathType Leaf) ?
(Get-Content -Path $PSScriptRoot/Defaults.json -Raw | ConvertFrom-Json) : @{}
# For backwards compatibility, the $DirectoryId argument is deprecated, $TenantId shall be used instead. Will be removed in future versions.
if ([string]::IsNullOrWhiteSpace($DirectoryId) -and ![string]::IsNullOrWhiteSpace($defaultsConfig.DirectoryId)) {
$DirectoryId = $defaultsConfig.DirectoryId
}
if ([string]::IsNullOrWhiteSpace($TenantId)) {
if (![string]::IsNullOrWhiteSpace($defaultsConfig.TenantId)) {
$TenantId = $defaultsConfig.TenantId
}
else {
$TenantId = $DirectoryId # For backwards compatibility
}
}
if ([string]::IsNullOrWhiteSpace($AzEnvironment)) {
if (![string]::IsNullOrWhiteSpace($defaultsConfig.AzEnvironment)) {
$AzEnvironment = $defaultsConfig.AzEnvironment
}
else {
$AzEnvironment = 'AzureCloud'
}
}
if ($defaultsConfig.PSobject.Properties.name -match "DontDeleteEmptyResourceGroups") {
try { $DontDeleteEmptyResourceGroups = [System.Convert]::ToBoolean($defaultsConfig.DontDeleteEmptyResourceGroups) } catch {}
}
if ($defaultsConfig.PSobject.Properties.name -match "AlwaysOnlyMarkForDeletion") {
try { $AlwaysOnlyMarkForDeletion = [System.Convert]::ToBoolean($defaultsConfig.AlwaysOnlyMarkForDeletion) } catch {}
}
if ($defaultsConfig.PSobject.Properties.name -match "EnableRegularResetOfRejectedState") {
try { $EnableRegularResetOfRejectedState = [System.Convert]::ToBoolean($defaultsConfig.EnableRegularResetOfRejectedState) } catch {}
}
if ($EnableRegularResetOfRejectedState -and $ResetOfRejectedStatePeriodInDays -lt 1) {
if ($defaultsConfig.ResetOfRejectedStatePeriodInDays -ge 1) {
$ResetOfRejectedStatePeriodInDays = $defaultsConfig.ResetOfRejectedStatePeriodInDays
}
else {
$ResetOfRejectedStatePeriodInDays = 180
}
}
if ($defaultsConfig.PSobject.Properties.name -match "TryMakingUserContributorTemporarily") {
try { $TryMakingUserContributorTemporarily = [System.Convert]::ToBoolean($defaultsConfig.TryMakingUserContributorTemporarily) } catch {}
}
if ($defaultsConfig.PSobject.Properties.name -match "CheckForUnusedResourceGroups") {
try { $CheckForUnusedResourceGroups = [System.Convert]::ToBoolean($defaultsConfig.CheckForUnusedResourceGroups) } catch {}
}
if ($defaultsConfig.PSobject.Properties.name -match "EnforceStdout") {
try { $EnforceStdout = [System.Convert]::ToBoolean($defaultsConfig.EnforceStdout) } catch {}
}
if ([string]::IsNullOrWhiteSpace($CentralAuditLogAnalyticsWorkspaceId) -and
![string]::IsNullOrWhiteSpace($defaultsConfig.CentralAuditLogAnalyticsWorkspaceId))
{
$CentralAuditLogAnalyticsWorkspaceId = $defaultsConfig.CentralAuditLogAnalyticsWorkspaceId
}
if ($MinimumResourceAgeInDaysForChecking -lt 1 -and $defaultsConfig.MinimumResourceAgeInDaysForChecking -ge 1) {
$MinimumResourceAgeInDaysForChecking = $defaultsConfig.MinimumResourceAgeInDaysForChecking
}
if ($DeleteSuspectedResourcesAndGroupsAfterDays -lt 0 -and $defaultsConfig.DeleteSuspectedResourcesAndGroupsAfterDays -ge 0) {
$DeleteSuspectedResourcesAndGroupsAfterDays = $defaultsConfig.DeleteSuspectedResourcesAndGroupsAfterDays
}
if ($SubscriptionIdsToProcess.Count -lt 1 -and $defaultsConfig.SubscriptionIdsToProcess -and
($defaultsConfig.SubscriptionIdsToProcess -is [System.Array]) -and
$defaultsConfig.SubscriptionIdsToProcess.Count -gt 0)
{
$SubscriptionIdsToProcess = $defaultsConfig.SubscriptionIdsToProcess
}
if ([string]::IsNullOrWhiteSpace($AutomationAccountResourceId) -and
![string]::IsNullOrWhiteSpace($defaultsConfig.AutomationAccountResourceId)) {
$AutomationAccountResourceId = $defaultsConfig.AutomationAccountResourceId
}
# Alert invalid parameter combinations
if ([string]::IsNullOrWhiteSpace($TenantId)) {
throw [System.ApplicationException]::new("TenantId is required")
return
}
if ($null -ne $ServicePrincipalCredential -and $UseSystemAssignedIdentity.IsPresent) {
throw [System.ApplicationException]::new("Parameters 'ServicePrincipalCredential' and 'UseSystemAssignedIdentity' cannot be used together")
return
}
if ($null -ne $ServicePrincipalCredential -and $UseDeviceAuthentication.IsPresent) {
throw [System.ApplicationException]::new("Parameters 'ServicePrincipalCredential' and 'UseDeviceAuthentication' cannot be used together")
return
}
if ($UseDeviceAuthentication.IsPresent -and $UseSystemAssignedIdentity.IsPresent) {
throw [System.ApplicationException]::new("Parameters 'UseDeviceAuthentication' and 'UseSystemAssignedIdentity' cannot be used together")
return
}
if ($null -ne $ServicePrincipalCredential -and [string]::IsNullOrEmpty($TenantId)) {
throw [System.ApplicationException]::new("Parameter 'ServicePrincipalCredential' requires 'TenantId' to be specified")
return
}
# Initialize static settings (non-parameterized)
$performDeletionWithoutConfirmation = $false # defensive default of $false (intentionally not made available as param)
$enableOperationalInsightsWorkspaceHook = $false # enable only when at least 30 days of Audit logs are available
$subjectForDeletionTagName = "SubjectForDeletion"
$subjectForDeletionFindingDateTagName = "SubjectForDeletion-FindingDate"
$subjectForDeletionReasonTagName = "SubjectForDeletion-Reason"
$resourceGroupOldAfterDays = 365 # resource groups with no deployments for that long and no write/action activities for 90 days
enum SubjectForDeletionStatus { # Supported values for the SubjectForDeletion tag
suspected
suspectedSubResources
rejected
confirmed
}
# General explanatory and constant tag/value applied to all tagged resource if value is not empty (e.g. URL to docs for the approach)
$subjectForDeletionHintTagName = "SubjectForDeletion-Hint"
$subjectForDeletionHintTagValue = "Update the '$subjectForDeletionTagName' tag to value '$([SubjectForDeletionStatus]::rejected.ToString())' if it shall not be deleted!"
if ([string]::IsNullOrWhiteSpace($DocumentationUrl) -and ![string]::IsNullOrWhiteSpace($defaultsConfig.DocumentationUrl)) {
$DocumentationUrl = $defaultsConfig.DocumentationUrl
}
if (![string]::IsNullOrWhiteSpace($DocumentationUrl)) {
$subjectForDeletionHintTagValue += " See also: $DocumentationUrl"
}
$tab = ' '
################################################################################
# Resource Type Hooks
################################################################################
# Actions decided upon by hooks
enum ResourceAction {
none
markForDeletion
markForSuspectSubResourceCheck
delete
}
# Resource type-specific hooks for determining the action to perform
function Test-ResourceActionHook-microsoft-batch-batchaccounts($Resource) {
$apps = Get-AzBatchApplication -ResourceGroupName $Resource.ResourceGroup -AccountName $Resource.Name -WarningAction Ignore
if ($apps.Id.Length -lt 1) {
return [ResourceAction]::markForDeletion, "The batch account has no apps."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-cache-redis($Resource) {
$periodInDays = 35
$totalGetCount = Get-Metric -ResourceId $Resource.Id -MetricName 'allgetcommands' -AggregationType Total -PeriodInDays $periodInDays
if ($null -ne $totalGetCount -and $totalGetCount.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The Redis cache had no read access for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-compute-disks($Resource) {
if ($Resource.Properties.diskState -ieq "Unattached" -or $Resource.ManagedBy.Length -lt 1)
{
return [ResourceAction]::markForDeletion, "The disk is not attached to any virtual machine."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-compute-images($Resource) {
$sourceVm = Get-AzResource -ResourceId $Resource.Properties.sourceVirtualMachine.Id
if ($sourceVm) {
Write-HostOrOutput "$($tab)$($tab)Source VM of a usually generalized image is still existing" -ForegroundColor DarkGray
return [ResourceAction]::markForDeletion, "The source VM (usually generalized) of the image still exists."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-compute-snapshots($Resource) {
$periodInDays = 180
if ($Resource.Properties.timeCreated -lt (Get-Date -AsUTC).AddDays(-$periodInDays)) {
return [ResourceAction]::markForDeletion, "The snapshot is older than $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-containerregistry-registries($Resource) {
$periodInDays = 90
$totalPullCount = Get-Metric -ResourceId $Resource.Id -MetricName 'TotalPullCount' -AggregationType Average -PeriodInDays $periodInDays
if ($null -ne $totalPullCount -and $totalPullCount.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The container registry had no pull requests for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-datafactory-factories($Resource) {
$periodInDays = 35
$totalSucceededActivityRuns = Get-Metric -ResourceId $Resource.Id -MetricName 'ActivitySucceededRuns' -AggregationType Total -PeriodInDays $periodInDays
if ($null -ne $totalSucceededActivityRuns -and $totalSucceededActivityRuns.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The data factory has no successful activity runs for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-dataprotection-backupvaults($Resource) {
$backupInstances = Get-AzDataProtectionBackupInstance -ResourceGroupName $Resource.ResourceGroup -VaultName $Resource.Name
if ($backupInstances.Count -lt 1) {
return [ResourceAction]::markForDeletion, "The backup vault has no backup instances."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-dbformysql-servers($Resource) {
$periodInDays = 35
$totalNetworkBytesEgress = Get-Metric -ResourceId $Resource.Id -MetricName 'network_bytes_egress' -AggregationType Total -PeriodInDays $periodInDays
if ($null -ne $totalNetworkBytesEgress -and $totalNetworkBytesEgress.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The MySql database had no egress for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-documentdb-databaseaccounts($Resource) {
$periodInDays = 35
$totalRequestCount = Get-Metric -ResourceId $Resource.Id -MetricName 'TotalRequests' -AggregationType Count -PeriodInDays $periodInDays
if ($null -ne $totalRequestCount -and $totalRequestCount.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The Document DB had no requests account for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-eventgrid-topics($Resource) {
$periodInDays = 35
$totalSuccessfulDeliveredEvents = Get-Metric -ResourceId $Resource.Id -MetricName 'DeliverySuccessCount' -AggregationType Total -PeriodInDays $periodInDays
if ($null -ne $totalSuccessfulDeliveredEvents -and $totalSuccessfulDeliveredEvents.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The event grid topic had no successfully delivered events for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-insights-activitylogalerts($Resource) {
if ($Resource.Properties.enabled -eq $false) {
return [ResourceAction]::markForDeletion, "The activity log alert is disabled."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-insights-components($Resource) {
$access = Get-AzAccessToken -ResourceTypeName "OperationalInsights"
$headers = @{"Authorization" = "Bearer " + $access.Token}
$body = @{ "timespan" = "P30D"; "query" = "requests | summarize totalCount=sum(itemCount)"} | ConvertTo-Json
$result = Invoke-RestMethod "https://api.applicationinsights.io/v1/apps/$($Resource.Properties.AppId)/query" -Method 'POST' -Headers $headers -Body $body -ContentType "application/json"
$totalRequestCount = $result.tables[0].rows[0][0]
if ($totalRequestCount -lt 1) {
return [ResourceAction]::markForDeletion, "The application insights resource had no read requests for 30 days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-insights-metricalerts($Resource) {
if ($Resource.Properties.enabled -eq $false) {
return [ResourceAction]::markForDeletion, "The metric alert is disabled."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-insights-scheduledqueryrules($Resource) {
if ($Resource.Properties.enabled -eq $false) {
return [ResourceAction]::markForDeletion, "The scheduled query rule is disabled."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-keyvault-vaults($Resource) {
$periodInDays = 35
$totalApiHits = Get-Metric -ResourceId $Resource.Id -MetricName 'ServiceApiHit' -AggregationType Count -PeriodInDays $periodInDays
if ($null -ne $totalApiHits -and $totalApiHits.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The key vault had no API hits for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-kusto-clusters($Resource) {
$periodInDays = 35
$totalReceivedBytesAverage = Get-Metric -ResourceId $Resource.Id -MetricName 'ReceivedDataSizeBytes' -AggregationType Average -PeriodInDays $periodInDays
if ($null -ne $totalReceivedBytesAverage -and $totalReceivedBytesAverage.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The Kusto cluster had no egress for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-logic-workflows($Resource) {
$periodInDays = 35
if ($Resource.Properties.state -ine 'Enabled') {
return [ResourceAction]::markForDeletion, "The logic apps workflow disabled."
}
$totalRunsSucceeded = Get-Metric -ResourceId $Resource.Id -MetricName 'RunsSucceeded' -AggregationType 'Total' -PeriodInDays $periodInDays
if ($null -ne $totalRunsSucceeded -and $totalRunsSucceeded.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The logic apps workflow had no successful runs for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-network-bastionhosts($Resource) {
$periodInDays = 35
$totalNumberOfSessions = Get-Metric -ResourceId $Resource.Id -MetricName 'sessions' -AggregationType Total -PeriodInDays $periodInDays
if ($null -ne $totalNumberOfSessions -and $totalNumberOfSessions.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The Bastion host had no sessions for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-network-connections($Resource) {
if ($Resource.Properties.connectionStatus -ine 'Connected') {
return [ResourceAction]::markForDeletion, "The network connection is disconnected."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-network-loadbalancers($Resource) {
$periodInDays = 35
if ($Resource.Properties.loadBalancingRules.Count -lt 1) {
return [ResourceAction]::markForDeletion, "The load balancer has no load blanancing rules."
}
if ($Resource.Sku.name -ine 'Basic') { # metrics not available in Basic SKU
$totalByteCount = Get-Metric -ResourceId $Resource.Id -MetricName 'ByteCount' -AggregationType Total -PeriodInDays $periodInDays
if ($null -ne $totalByteCount -and $totalByteCount.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The load balancer had no transmitted bytes for $periodInDays days."
}
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-network-networkinterfaces($Resource) {
if (!$Resource.Properties.virtualMachine -and !$Resource.Properties.privateEndpoint) {
return [ResourceAction]::markForDeletion, "The network interface is unassigned."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-network-networksecuritygroups($Resource) {
if (!$Resource.Properties.networkInterfaces -and !$Resource.Properties.subnets) {
return [ResourceAction]::markForDeletion, "The network security group is unassigned."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-network-publicipaddresses($Resource) {
if ($null -eq $Resource.Properties.ipConfiguration.id)
{
return [ResourceAction]::markForDeletion, "The public IP address is unassigned."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-network-routetables($Resource) {
$atLeastOneUsedRoute = $false
foreach ($route in $Resource) {
if ($route.properties.subnets.Count -gt 0) {
$atLeastOneUsedRoute = $true
}
}
if (!$atLeastOneUsedRoute) {
return [ResourceAction]::markForDeletion, "The network route table has no used routed."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-network-trafficmanagerprofiles($Resource) {
if ($Resource.Properties.profileStatus -ine 'Enabled') {
return [ResourceAction]::markForDeletion, "The traffic manager profile is disabled."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-network-virtualnetworks($Resource) {
if ($Resource.Properties.subnets.Count -lt 1) {
return [ResourceAction]::markForDeletion, "The virtual network has no subnets."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-notificationhubs-namespaces($Resource) {
$parameters = @{
ResourceType = 'Microsoft.NotificationHubs/namespaces/notificationHubs'
ResourceGroupName = $Resource.ResourceGroup
ResourceName = $Resource.Name
ApiVersion = '2017-04-01'
}
$notificationHub = Get-AzResource @parameters
if ($null -eq $notificationHub) {
return [ResourceAction]::markForDeletion, "The notification hub has no hubs."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-operationalinsights-workspaces($Resource) {
#
# NOTE: This hook is only working for LogAnalytics workspaces which have diagnostic
# 'Audit' logs enabled and written into either the workspace itself or another single
# workspace specified in $CentralAuditLogAnalyticsWorkspaceId. Therefore, to enable
# this hook, the following setting must be made:
# $enableOperationalInsightsWorkspaceHook = $true
#
$periodInDays = 35 # data retention in the LogAnalytics workspaces needs to be configured correspondingly
if ($enableOperationalInsightsWorkspaceHook -eq $true) {
$query = "LAQueryLogs | where TimeGenerated >= now() - $($periodInDays)d | where RequestTarget == '$($Resource.Id)' | count"
$numberOfUserOrClientRequests = 0
if (![string]::IsNullOrWhiteSpace($CentralAuditLogAnalyticsWorkspaceId)) {
$results = Invoke-AzOperationalInsightsQuery -Query $query -WorkspaceId $CentralAuditLogAnalyticsWorkspaceId | Select-Object -ExpandProperty Results
$numberOfUserOrClientRequests = [int]$results[0].Count
}
if ($numberOfUserOrClientRequests -lt 1) {
$workspace = Get-AzOperationalInsightsWorkspace -ResourceGroupName $Resource.ResourceGroup -Name $Resource.Name
$results = Invoke-AzOperationalInsightsQuery -Query $query -WorkspaceId $workspace.CustomerId | Select-Object -ExpandProperty Results
$numberOfUserOrClientRequests = [int]$results[0].Count
}
if ($numberOfUserOrClientRequests -lt 1) {
return [ResourceAction]::markForDeletion, "The log analytics workspace had no read requests for $periodInDays days."
}
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-servicebus-namespaces($Resource) {
$queues = Get-AzServiceBusQueue -ResourceGroupName $Resource.ResourceGroup -NamespaceName $Resource.Name
$result = [ResourceAction]::none
foreach ($queue in $queues) {
if ($queue.Status -ine "Active") {
Write-HostOrOutput "$($tab)$($tab)Queue '$($queue.name)' is in status '$($queue.Status)'" -ForegroundColor DarkGray
$result = [ResourceAction]::markForSuspectSubResourceCheck, "The service bus namespace has at least one inactive queue."
}
}
return $result, ""
}
function Test-ResourceActionHook-microsoft-web-serverfarms($Resource) {
if ($Resource.Properties.numberOfSites -lt 1) {
return [ResourceAction]::markForDeletion, "The app service plan has no apps."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-web-sites-functionapp($Resource) {
if ($Resource.Properties.state -ieq 'Running') { # we can't see functions in stopped apps, so we ignore them
$GetAzResourceParameters = @{
ResourceType = 'Microsoft.Web/sites/functions'
ResourceGroupName = $Resource.ResourceGroup
ResourceName = $Resource.Name
ApiVersion = '2022-03-01'
}
$functions = Get-AzResource @GetAzResourceParameters
if ($nul -eq $functions) {
Write-HostOrOutput "$($tab)$($tab)Function app has no functions" -ForegroundColor DarkGray
return [ResourceAction]::markForDeletion, "The function app has no functions."
}
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-web-sites-functionapp-linux($Resource) {
return Test-ResourceActionHook-microsoft-web-sites-functionapp($Resource)
}
function Test-ResourceActionHook-microsoft-web-sites-functionapp-linux-container($Resource) {
return Test-ResourceActionHook-microsoft-web-sites-functionapp($Resource)
}
function Test-ResourceActionHook-microsoft-web-sites-app($Resource) {
$periodInDays = 35
$webApp = Get-AzWebApp -ResourceGroupName $Resource.ResourceGroup -Name $Resource.Name
if ($null -eq $webApp) {
return [ResourceAction]::none, "Web App does not exist."
}
if ($webApp.State -eq 'Stopped') {
$lastModifiedTime = $webApp.SiteConfig.LastModifiedTimeUtc
if ($null -eq $lastModifiedTime) {
$webApp.LastModifiedTimeUtc
}
if ($null -ne $lastModifiedTime) {
$currentTime = (Get-Date).ToUniversalTime()
$timeDiff = $currentTime - $lastModifiedTime
if ($timeDiff.Days -gt $periodInDays) {
return [ResourceAction]::markForDeletion, "Web App has been stopped for more than $periodInDays days."
}
}
}
$cpuUtilization = Get-Metric -ResourceId $Resource.Id -MetricName 'CpuTime' -AggregationType 'Total' -PeriodInDays $periodInDays
if ($null -ne $cpuUtilization -and $cpuUtilization.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The web app had no CPU utilization for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-web-sites-app-linux($Resource) {
return Test-ResourceActionHook-microsoft-web-sites-app($Resource)
}
function Test-ResourceActionHook-microsoft-web-sites-app-linux-container($Resource) {
return Test-ResourceActionHook-microsoft-web-sites-app($Resource)
}
function Test-ResourceActionHook-microsoft-storage-storageaccounts($Resource) {
$periodInDays = 35
$totalNumOfTransactions = Get-Metric -ResourceId $Resource.Id -MetricName "Transactions" -AggregationType "Total" -PeriodInDays $periodInDays
if ($null -ne $totalNumOfTransactions -and $totalNumOfTransactions.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The storage account had no transactions for $periodInDays days."
}
$usedCapacity = Get-Metric -ResourceId $Resource.Id -MetricName "UsedCapacity" -AggregationType "Average" -PeriodInDays $periodInDays -TimeGrainInHours 1
if ($null -ne $usedCapacity -and $usedCapacity.Maximum -lt 1) {
return [ResourceAction]::markForDeletion, "The storage account had no data for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-apimanagement-service($Resource) {
$periodInDays = 35
$apimContext = New-AzApiManagementContext -ResourceGroupName $Resource.ResourceGroup -ServiceName $Resource.Name
$apis = Get-AzApiManagementApi -Context $apimContext
if ($apis.Count -eq 0) {
return [ResourceAction]::markForDeletion, "API Management service has no APIs deployed."
}
$numberOfTotalRequests = Get-Metric -ResourceId $Resource.Id -MetricName "TotalRequests" -AggregationType "Total" -PeriodInDays $periodInDays
if ($numberOfTotalRequests.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "API Management service has had no traffic in the last $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-compute-virtualmachines($Resource) {
$periodInDays = 35
$vmStatus = Get-AzVM -Status -ResourceGroupName $Resource.ResourceGroup -VMName $Resource.Name
if ($vmStatus.Statuses[1].Code -eq 'PowerState/deallocated' -or $vmStatus.Statuses[1].Code -eq 'PowerState/stopped') {
$lastStatusChange = $vmStatus.Statuses[1].Time
if ($null -ne $lastStatusChange) {
$currentTime = Get-Date
$timeDiff = $currentTime - $lastStatusChange
if ($timeDiff.Days -gt $periodInDays) {
return [ResourceAction]::markForDeletion, "VM has been stopped for more than $periodInDays days."
}
}
}
$cpuUtilization = Get-Metric -ResourceId $Resource.Id -MetricName 'Percentage CPU' -AggregationType 'Average' -PeriodInDays $periodInDays
if ($null -ne $cpuUtilization -and $cpuUtilization.Average -lt 1) {
return [ResourceAction]::markForDeletion, "The VM had no CPU utilization for $periodInDays days."
}
$networkUtilization = Get-Metric -ResourceId $Resource.Id -MetricName 'Network In' -AggregationType 'Total' -PeriodInDays $periodInDays
if ($null -ne $networkUtilization -and $networkUtilization.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The VM had no network traffic for $periodInDays days."
}
$diskUtilization = Get-Metric -ResourceId $Resource.Id -MetricName 'Disk Read Bytes' -AggregationType 'Total' -PeriodInDays $periodInDays
if ($null -ne $diskUtilization -and $diskUtilization.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The VM had no disk read activity for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-compute-virtualmachinescalesets($Resource) {
$periodInDays = 30
if ($Resource.Sku.Capacity -eq 0) {
return [ResourceAction]::markForDeletion, "VMSS has no instances."
}
$vmssInstances = Get-AzVmssVM -ResourceGroupName $Resource.ResourceGroup -VMScaleSetName $Resource.Name
$allStopped = $true
$message = "All instances in VMSS have been stopped."
$currentTime = Get-Date
foreach ($instance in $vmssInstances) {
$instanceView = Get-AzVmssVM -ResourceGroupName $Resource.ResourceGroup -VMScaleSetName $Resource.Name -InstanceId $instance.InstanceId -InstanceView
$powerState = $instanceView.Statuses | Where-Object { $_.Code -match 'PowerState/' } | Select-Object -ExpandProperty Code
if ($powerState -ne 'PowerState/deallocated' -and $powerState -ne 'PowerState/stopped') {
$allStopped = $false
break
}
$lastStatusChange = $instanceView.Statuses | Where-Object { $_.Code -match 'PowerState/' } | Select-Object -ExpandProperty Time
if ($null -ne $lastStatusChange) {
$timeDiff = $currentTime - $lastStatusChange
if ($timeDiff.Days -le $periodInDays) {
$allStopped = $false
break
}
$message = "All instances in VMSS have been stopped for more than $periodInDays days."
}
}
if ($allStopped) {
return [ResourceAction]::markForDeletion, $message
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-virtualmachineimages-imagetemplates($Resource) {
$failedPeriodInDays = 35
$updatePeriodInDays = 365
if ($Resource.Properties.source.type -eq 'PlatformImage') {
if ($Resource.Properties.lastRunStatus.runState -eq "Failed" -and $Resource.Properties.lastRunStatus.endTime -lt (Get-Date).AddDays(-$failedPeriodInDays)) {
return [ResourceAction]::markForDeletion, "The image template build failed and was more than $failedPeriodInDays days ago."
}
if ($Resource.Properties.lastRunStatus.runState -ne "Failed" -and $Resource.Properties.lastRunStatus.endTime -lt (Get-Date).AddDays(-$updatePeriodInDays)) {
return [ResourceAction]::markForDeletion, "The image template was not updated for more than $updatePeriodInDays days."
}
if ($Resource.Properties.distribute.Count -lt 1 -or ($null -eq $Resource.Properties.distribute[0].galleryImageId)) {
return [ResourceAction]::markForDeletion, "The image template has no image to distribute."
}
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-containerinstance-containergroups($Resource) {
$periodInDays = 35
$currentTime = Get-Date
if ($Resource.Properties.InstanceView.State -eq 'Stopped') {
$lastInstanceViewEvent = $Resource.Properties.InstanceView.Events | Sort-Object -Property LastTimestamp -Descending | Select-Object -First 1
if ($null -ne $lastInstanceViewEvent -and $lastInstanceViewEvent.Name -eq 'DeploymentFailed') {
$timeDiff = $currentTime - $lastInstanceViewEvent.LastTimestamp
if ($timeDiff.Days -gt $periodInDays) {
return [ResourceAction]::markForDeletion, "Container Group deployment failed more than $periodInDays days ago."
}
}
$Resource.Properties.Containers | ForEach-Object {
$lastContainerInstanceViewEvent = $_.Properties.InstanceView.Events | Sort-Object -Property LastTimestamp -Descending | Select-Object -First 1
if ($null -ne $lastContainerInstanceViewEvent) {
if ($lastContainerInstanceViewEvent.Name -eq 'Killing' -or $lastContainerInstanceViewEvent.Name -eq 'Failed') {
$timeDiff = $currentTime - $lastContainerInstanceViewEvent.LastTimestamp
if ($timeDiff.Days -gt $periodInDays) {
return [ResourceAction]::markForDeletion, "All containers failed or killed more than $periodInDays days ago."
}
}
}
}
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-network-applicationgateways($Resource) {
$periodInDays = 35
$hasBackendPools = $Resource.Properties.BackendAddressPools.Count -gt 0
if (-not $hasBackendPools) {
return [ResourceAction]::markForDeletion, "Application Gateway has no backend pool instances."
}
$totalBytesReceived = Get-Metric -ResourceId $Resource.Id -MetricName 'BytesReceived' -AggregationType 'Total' -PeriodInDays $periodInDays
if ($null -ne $totalBytesReceived -and $totalBytesReceived.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "Application Gateway had no received bytes for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-sql-servers($Resource) {
$periodInDays = 35
$activeDatabases = Get-AzSqlDatabase -ServerName $Resource.name -ResourceGroupName $Resource.resourceGroup | Where-Object { $_.Status -eq 'Online' -and $_.DatabaseName -ne 'master' }
if ($activeDatabases.Count -lt 1) {
return [ResourceAction]::markForDeletion, "The SQL server has no databases."
}
$valid = $false
$used = $false
foreach ($database in $activeDatabases) {
$avgDtuUsed = Get-Metric -ResourceId $database.ResourceId -MetricName 'dtu_consumption_percent' -AggregationType 'Average' -PeriodInDays $periodInDays
if ($null -ne $avgDtuUsed) {
$valid = $true
if ($avgDtuUsed.Average -gt 0) {
$used = $true
}
}
}
if ($valid -and !$used) {
return [ResourceAction]::markForDeletion, "The SQL server had no DTU consumption for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-portal-dashboards($Resource) {
$lenses = $Resource.Properties.Lenses
if ($lenses.Count -lt 1) {
return [ResourceAction]::markForDeletion, "The dashboard has no content."
}
$overallNumParts = 0
$overallNumInputs = 0
foreach ($lens in $lenses) {
$parts = $lens.parts
if ($null -ne $parts) {
$overallNumParts += $parts.Count
foreach ($part in $parts) {
$inputs = $part.metadata.inputs
if ($null -ne $inputs) {
$overallNumInputs += $inputs.Count
}
}
}
}
if ($overallNumParts -lt 1) {
return [ResourceAction]::markForDeletion, "The dashboard has no parts."
}
if ($overallNumInputs -lt 1) {
return [ResourceAction]::markForDeletion, "None of the parts on the dashboard has inputs."
}
$title = $null
if ($Resource.Tags) {
$title = $Resource.Tags.'hidden-title'
}
if ($null -eq $title -or $title -match '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}') {
return [ResourceAction]::markForDeletion, "The dashboard has no readable title, is it a temporary one?"
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-app-containerapps($Resource) {
$periodInDays = 35
$isRunning = $Resource.Properties.RunningStatus -eq 'Running'
if (!$isRunning) {
return [ResourceAction]::markForDeletion, "The container app is not running."
}
$hasContainers = $Resource.Properties.Template.Containers.Count -gt 0
if (!$hasContainers) {
return [ResourceAction]::markForDeletion, "The container app has no containers."
}
$avgCpuUsageInfo = Get-Metric -ResourceId $Resource.Id -MetricName 'UsageNanoCores' -AggregationType 'Average' -PeriodInDays $periodInDays
if ($null -ne $avgCpuUsageInfo) {
$avgCpuUsage = $avgCpuUsageInfo.Average / 1000000000
if ($avgCpuUsage -eq 0) {
return [ResourceAction]::markForDeletion, "The container app had no CPU utilization for $periodInDays days."
}
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-app-managedenvironments($Resource) {
$numOfContainerApps = Get-AzContainerApp -ResourceGroupName $Resource.resourceGroup | Where-Object { $_.ManagedEnvironmentId -ieq $Resource.Id }
if ($numOfContainerApps.Count -lt 1) {
return [ResourceAction]::markForDeletion, "The managed Container Apps environment has no container apps."
}
$atLeastOneAppProvisionedSuccessfully = $false
foreach ($containerApp in $numOfContainerApps) {
if ($containerApp.ProvisioningState -ieq 'Succeeded') {
$atLeastOneAppProvisionedSuccessfully = $true
break
}
}
if (!$atLeastOneAppProvisionedSuccessfully) {
return [ResourceAction]::markForDeletion, "The managed Container Apps environment has no successfully provisioned container apps."
}
$atLeastOneAppIsNotSubjectToDeletion = $false
foreach ($containerApp in $numOfContainerApps) {
$tags = $containerApp.Tags
$isSubjectForDeletion = ($null -ne $tags) -and ($tags.SubjectForDeletion ?? "") -ilike 'suspected*'
if (!$isSubjectForDeletion) {
$atLeastOneAppIsNotSubjectToDeletion = $true
break
}
}
if (!$atLeastOneAppIsNotSubjectToDeletion) {
return [ResourceAction]::markForDeletion, "All container apps in the managed Container Apps environment are subject for deletion."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-cdn-profiles-cdn($Resource) {
$periodInDays = 35
$isActive = $Resource.Properties.ResourceState -eq 'Active'
if (!$isActive) {
return [ResourceAction]::markForDeletion, "The classic CDN profile is not active."
}
$cdnProfile = Get-AzCdnProfile -ResourceGroupName $Resource.ResourceGroup -ProfileName $Resource.Name
$endpoints = Get-AzCdnEndpoint -ResourceGroupName $Resource.ResourceGroup -ProfileName $Resource.Name
if ($endpoints.Count -lt 1) {
return [ResourceAction]::markForDeletion, "The classic CDN profile has no endpoints."
}
$atLeastOneEndpointEnabled = $false
foreach ($endpoint in $endpoints) {
$origins = $endpoint.Origin
foreach ($origin in $origins) {
if ($origin.Enabled) {
$atLeastOneEndpointEnabled = $true
break
}
}
}
if (!$atLeastOneEndpointEnabled) {
return [ResourceAction]::markForDeletion, "The classic CDN profile has no enabled endpoints."
}
$requestCountInfo = Get-Metric -ResourceId $cdnProfile.Id -MetricName 'RequestCount' -AggregationType 'Total' -PeriodInDays $periodInDays
if ($null -ne $requestCountInfo -and $requestCountInfo.Sum -lt 1) {
return [ResourceAction]::markForDeletion, "The classic CDN profile had no requests for $periodInDays days."
}
return [ResourceAction]::none, ""
}
function Test-ResourceActionHook-microsoft-cdn-profiles-frontdoor($Resource) {
$periodInDays = 35
$isActive = $Resource.Properties.ResourceState -eq 'Active'
if (!$isActive) {
return [ResourceAction]::markForDeletion, "The Frontdoor CDN profile is not active."
}
$cdnProfile = Get-AzFrontDoorCdnProfile -ResourceGroupName $Resource.ResourceGroup -Name $Resource.Name
$endpoints = Get-AzFrontDoorCdnEndpoint -ResourceGroupName $Resource.ResourceGroup -ProfileName $cdnProfile.Name
$atLeastOneEndpointEnabled = $false
$atLeastOneEndpointHasEnabledRoutes = $false
foreach ($endpoint in $endpoints) {
$isEnabled = $endpoint.EnabledState -eq 'Enabled'