-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMigration.ps1
More file actions
3443 lines (2945 loc) · 150 KB
/
Copy pathMigration.ps1
File metadata and controls
3443 lines (2945 loc) · 150 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 runbook is intended to help customers migrate their machines and schedules onboarded to the legacy Azure Update Management using Automation solution to the latest Azure Update Manager solution.
This script will enable periodic assessment for machines and migrate software update configurations to MRP maintenance configurations.
.DESCRIPTION
This runbook will do one of the below based on the parameters provided to it.
The runbook will be using the User-Assigned Managed Identity whose client id is passed as a parameter for authenticating ARM calls. Please ensure the managed idenity is assigned the proper role definitions before executing this runbook.
Non-Azure machines which are not onboarded to Arc will not be onboarded to Azure Update Manager.
1. If EnablePeriodicAssessmentForMachinesOnboardedToUpdateManagement parameter is true, it will enable periodic assessment for all azure/arc machines onboarded to Automation Update Management under the automation account where the runbook is executing.
2. if MigrateSchedulesAndEnablePeriodicAssessmentForLinkedMachines parameters is true,
2.1. It will enable periodic asssessment for all azure/arc machines either attached or picked up through azure dynamic queries of software update configurations under the automation account where the runbook is executing.
2.2. It will set required patch properties for scheduled patching for all azure machines either attached or picked up through dynamic queries of software update configurations under the automation account where the runbook is executing.
2.3. It will migrate software update configurations by creating equivalent MRP maintenance configurations. Maintenance configurations will be created in the region where the automation account resides and in the resource group provided as input.
2.3.1. Pre/Post tasks of software update configurations will be migrated. It will create automation webhooks and event grid subscriptions for the same.
2.3.2. Saved search queries of software update configurations will not be migrated.
.PARAMETER AutomationAccountResourceId
Mandatory
Automation Account Resource Id.
.PARAMETER UserManagedServiceIdentityClientId
Mandatory
Client Id of the User Assigned Managed Idenitity.
.PARAMETER EnablePeriodicAssessmentForMachinesOnboardedToUpdateManagement
Optional
.PARAMETER MigrateSchedulesAndEnablePeriodicAssessmentForLinkedMachines
Optional
.PARAMETER ResourceGroupNameForMaintenanceConfigurations
Optional
Please provide resource group name when migrating software update configurations.
The resource group name should not be more than 36 characters.
The resource group name which will be used for creating a resource group in the same region as the automation account. The maintenance configurations for the migrated software update configurations from the automation account will be residing here.
.EXAMPLE
Migration -AutomationAccountResourceId "/subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Automation/automationAccounts/{aaName}" -ClientId "########-####-####-####-############" -EnablePeriodicAssessment $true MigrateSchedulesAndEnablePeriodicAssessmentForLinkedMachines $true
.OUTPUTS
Outputs the status of machines and software update configurations post migration to the output stream.
#>
param(
[Parameter(Mandatory = $true)]
[String]$AutomationAccountResourceId,
[Parameter(Mandatory = $true)]
[String]$UserManagedServiceIdentityClientId,
[Parameter(Mandatory = $false)]
[bool]$EnablePeriodicAssessmentForMachinesOnboardedToUpdateManagement=$true,
[Parameter(Mandatory = $false)]
[bool]$MigrateSchedulesAndEnablePeriodicAssessmentForLinkedMachines=$true,
[Parameter(Mandatory = $false)]
[String]$ResourceGroupNameForMaintenanceConfigurations
)
# Telemetry level.
$Debug = "Debug"
$Verbose = "Verbose"
$Informational = "Informational"
$Warning = "Warning"
$ErrorLvl = "Error"
# Supported machine resource types.
$AzureVM = "AzureVM"
$ArcServer = "ArcServer"
$NonAzureMachine = "NonAzureMachine"
# Supported OS types.
$Windows = "Windows"
$Linux = "Linux"
# Patch settings status.
$NotAttempted = "NotAttempted"
$Succeeded = "Succeeded"
$Failed = "Failed"
# Supported in Azure Update Manager.
$NotEvaluated = "NotEvaluated"
$Supported = "Supported"
$NotSupported = "NotSupported"
# Software update configuration provisioning state.
$SoftwareUpdateConfigurationSucceededProvisioningState = "Succeeded"
# SUC to MRP reboot settings mapping.
$SoftwareUpdateConfigurationToMaintenanceConfigurationRebootSetting = @{
"IfRequired" = "IfRequired";
"Never" = "NeverReboot";
"Always" = "AlwaysReboot";
}
$RebootOnly = "RebootOnly"
# Configuration frequency settings.
$OneTime = "OneTime"
$Hour = "Hour"
$Hours = "Hours"
$Day = "Day"
$Days = "Days"
$Week = "Week"
$Weeks = "Weeks"
$Month = "Month"
$Months = "Months"
# Configuration Assignment Tag.
$MigrationTag = "AUMMig"
# MRP schedule configurations.
$MRPScheduleMaxAllowedDuration = "04:00"
$MRPScheduleMinAllowedDuration = "01:30"
$MRPScheduleDateFormat = "yyyy-MM-dd HH:mm"
# Webhook configurations.
$WebhookExpiryDateFormat = "yyyy-MM-ddTHH:mm:ss"
$PreTaskWebhook = "PreTaskWebhook"
$PostTaskWebhook = "PostTaskWebhook"
# SUC to MRP reboot settings mapping.
$SoftwareUpdateConfigurationToMaintenanceConfigurationPatchDaySetting = @{
"1" = "First";
"2" = "Second";
"3" = "Third";
"4" = "Fourth";
"-1" = "Last"
}
# Dynamic scope global level.
$MaintenanceConfigurationDynamicAssignmentGlobalScope = "global"
# Master runbook name
$MasterRunbookName = "Patch-MicrosoftOMSComputers"
# Software update configuration migration status.
$NotMigrated = "NotMigrated"
$MigrationFailed = "MigrationFailed"
$Migrated = "Migrated"
$PartiallyMigrated = "PartiallyMigrated"
# ARM resource providers.
$ResourceGraphRP = "Microsoft.ResourceGraph";
# ARM resource types.
$VMResourceType = "virtualMachines";
$ArcVMResourceType = "machines";
$ArgResourcesResourceType = "resources";
# API versions.
$VmApiVersion = "2023-09-01";
$ArcVmApiVersion = "2022-12-27";
$AutomationApiVersion = "2022-08-08"
$SoftwareUpdateConfigurationApiVersion = "2023-11-01";
$AutomationAccountApiVersion = "2023-11-01";
$ResourceGraphApiVersion = "2021-03-01";
$MaintenanceConfigurationpApiVersion = "2023-04-01";
$ResourceGroupApiVersion = "2021-04-01";
$WebhookApiVersion = "2015-10-31";
$EventGridApiVersion = "2023-12-15-preview"
# HTTP methods.
$GET = "GET"
$PATCH = "PATCH"
$PUT = "PUT"
$POST = "POST"
$DELETE = "DELETE"
# ARM endpoints.
$LinkedWorkspacePath = "{0}/linkedWorkspace"
$SoftwareUpdateConfigurationsPath = "{0}/softwareUpdateConfigurations?`$skip={1}"
$AutomationSchedulesPath = "{0}/Schedules/{1}"
$JobSchedulesWithPatchRunbookFilterPath = "{0}/JobSchedules/?$filter=properties/runbook/name%20eq%20'Patch-MicrosoftOMSComputers'&`$skip={1}"
$MaintenanceConfigurationAssignmentPath = "{0}/providers/Microsoft.Maintenance/configurationAssignments/{1}"
$ResourceGroupPath = "{0}/resourceGroups/{1}"
$WebhookPath = "{0}/webhooks/{1}"
$SystemTopicPath = "{0}/providers/Microsoft.EventGrid/systemTopics/{1}"
$EventSubscriptionPath = "{0}/providers/Microsoft.EventGrid/eventSubscriptions/{1}"
# Error codes.
$Unknown = "Unknown"
$UnhandledException = "UnhandledException"
$NotOnboardedToArcErrorCode = "NotOnboardedToArc"
$NotFoundErrorCode = "404"
# Error messages.
$NotOnboardedToArcErrorMessage = "The machine is not onboarded to ARC. Onboard your machine to ARC to migrate it to AUM, more details here: https://aka.ms/OnboardToArc"
$SoftwareUpdateConfigurationNotProvisionedSuccessfully = "The software update configuration is not provisioned successfully."
$SoftwareUpdateConfigurationInErroredState = "The software update configuration is in errored state."
$FailedToCreateMaintenanceConfiguration = "Failed to create maintenance configuration."
$ExpiredSoftwareUpdateConfigurationMessage = "The software update configuration is already expired."
$DisabledSoftwareUpdateConfigurationMessage = "The associated schedule for the software update configuration is disabled."
$ConfigurationAssignmentFailedForMachines = "Configuration assignment failed for few machines."
$FailedToResolveDynamicAzureQueries = "Failed to resolve few dynamic azure queries."
$FailedToAssignDynamicAzureQueries = "Failed to assign dynamic scopes."
$SoftwareUpdateConfigurationHasSavedSearchQueries = "The software update configuration has saved search queries for non-azure machines. Please create equivalent dynamic scope manually."
$SoftwareUpdateConfigurationHasPrePostTasks = "The software update configuration has pre/post tasks which were not successfully assigned to maintenance configuration."
$SoftwareUpdateConfigurationHasRebootOnlySetting = "The software update configuration has reboot only as the reboot option which is not supported in Azure Update Manager."
# ARG constants.
$ScopeRgRegExPattern = "/subscriptions/[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}/resourceGroups/[^/]*[/]?$";
$ScopeSubscriptionRegExPattern = "/subscriptions/[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}[/]?$";
$TagFilterClause = "tags[tolower(\""{0}\"")] =~ \""{1}\""";
$VirtualMachinesWhereClause = "where (type =~ \""microsoft.compute/virtualmachines\""";
$ResourceGroupWhereClause = $VirtualMachinesWhereClause + " and resourceGroup in~ ({0})";
$WhereClause = " | where "
$ArgQueryProjectClause = " | project id, location, name, tags = todynamic(tolower(tostring(tags)))";
$ArgQueryOsTypeClause = " | where properties.storageProfile.osDisk.osType =~ \""{0}\""";
$ArgQueryPatchSettingsClause = "| extend patchSettings = coalesce(properties.osProfile.windowsConfiguration.patchSettings, properties.osProfile.linuxConfiguration.patchSettings)
| extend assessmentMode = tostring(patchSettings.assessmentMode), patchMode = tostring(patchSettings.patchMode), bypassPlatformSafetyChecksOnUserSchedule = tostring(patchSettings.automaticByPlatformSettings.bypassPlatformSafetyChecksOnUserSchedule)"
$ArgDynamicScopeConfigurationAssignmentsClause = "MaintenanceResources
| where type =~ \""microsoft.maintenance/configurationassignments\""
| where properties.maintenanceConfigurationId =~ \""{0}\""
| where properties.resourceId !has \""providers/\""
| extend resourceId = tostring(properties.resourceId)
| project id, type, resourceGroup, subscriptionId, tenantId, location, name, properties";
$AndParam = " and ";
$OrParam = " or ";
$CommaSeparator = ",";
$ForwardSlashSeparator = "/";
$QuoteParam = """";
# Validation values.
$ResourceTypes = @($AzureVM, $ArcServer, $NonAzureMachine)
$OsTypes = @($Windows, $Linux)
$PatchSettingsStatus = @($NotAttempted, $Succeeded, $Failed)
$TelemetryLevels = @($Debug, $Verbose, $Informational, $Warning, $ErrorLvl)
$MachineResourceTypes = @($VMResourceType, $ArcVMResourceType)
$HttpMethods = @($GET, $PATCH, $POST, $PUT, $DELETE)
# Time Zones List for Backward Compatability
$TimeZonesBackwardCompatability = @{
"America/Nuuk" = "America/Godthab";
"Asia/Kolkata" = "Asia/Calcutta";
"Asia/Kathmandu" = "Asia/Katmandu";
"Asia/Yangon" = "Asia/Rangoon";
"Asia/Ho_Chi_Minh" = "Asia/Saigon";
"Atlantic/Faroe" = "Atlantic/Faeroe";
"Europe/Kyiv" = "Europe/Kiev"
}
# Class for assessment, pathching and error details of machine for onboarding to Azure Update Manager.
class MachineReadinessData
{
[String]$ResourceId
[String]$ComputerName
[String]$ResourceType
[String]$OsType
[String]$PeriodicAssessmentStatus
[String]$ScheduledPatchingStatus
[String]$ErrorCode
[String]$ErrorMessage
[void] UpdateMachineStatus(
[String]$resourceId,
[String]$computerName,
[String]$resourceType,
[String]$osType,
[String]$periodicAssessmentStatus = $NotAttempted,
[String]$scheduledPatchingStatus = $NotAttempted,
[String]$errorCode,
[String]$errorMessage)
{
<#
.SYNOPSIS
Updates status of machines in regards to assessment or scheduled patching status.
.DESCRIPTION
This function will add/edit machine readiness data.
.PARAMETER resourceId
ARM resourceId of the machine.
.PARAMETER computerName
Computer name.
.PARAMETER resourceType
Resource type.
.PARAMETER osType
OS type.
.PARAMETER preriodicAssessmentStatus
AssessmentMode status.
.PARAMETER scheduledPatchingStatus
Scheduled patching status.
.PARAMETER errorCode
Error code for setting machine status.
.PARAMETER errorMessage
Error message for setting machine status.
#>
$this.ResourceId = $resourceId
$this.ComputerName = $computerName
$this.ResourceType = $resourceType
$this.OsType = $osType
$this.PeriodicAssessmentStatus = $periodicAssessmentStatus
$this.ScheduledPatchingStatus = $scheduledPatchingStatus
$this.ErrorCode = $errorCode
$this.ErrorMessage = $errorMessage
}
}
# Class for machine association details with respect to software update configuration for onboarding to Azure Update Manager.
class MachineReadinessDataForSoftwareUpdateConfiguration
{
[String]$ResourceId
[bool]$IsConfigAssignmentRequired
[bool]$IsConfigAssignmentSuccessful
[bool]$IsMachineResolvedThroughAzureDynamicQuery
[String]$ErrorCode
[String]$ErrorMessage
}
# Class for dynamic azure queries association details with respect to software update configuration.
class DynamicAzureQueriesDataForSoftwareUpdateConfiguration
{
[bool]$HasDynamicAzureQueries
[bool]$AllDynamicAzureQueriesSuccessfullyResolved
[bool]$AllDynamicAzureQueriesSuccessfullyAssigned
}
# Class for pre and post tasks association details with respect to software update configuration.
class PrePostDataForSoftwareUpdateConfiguration
{
[bool]$HasPreTasks
[bool]$PreTasksAssignedSuccessfully
[bool]$HasPostTasks
[bool]$PostTasksAssignedSuccessfully
}
# Class for software update configuration migration details.
class SoftwareUpdateConfigurationMigrationData
{
[String]$SoftwareUpdateConfigurationResourceId
[String]$MaintenanceConfigurationResourceId
[String]$OperatingSystem
[System.Collections.Hashtable]$MachinesReadinessDataForSoftwareUpdateConfiguration
[DynamicAzureQueriesDataForSoftwareUpdateConfiguration]$DynamicAzureQueriesStatus
[PrePostDataForSoftwareUpdateConfiguration]$PrePostStatus
[bool]$HasSavedSearchQueries
[String]$MigrationStatus
[System.Collections.ArrayList]$ErrorMessage
[bool]$UnderlyingScheduleDisabled
SoftwareUpdateConfigurationMigrationData()
{
$this.MachinesReadinessDataForSoftwareUpdateConfiguration = @{}
$this.DynamicAzureQueriesStatus = [DynamicAzureQueriesDataForSoftwareUpdateConfiguration]::new()
$this.PrePostStatus = [PrePostDataForSoftwareUpdateConfiguration]::new()
$this.ErrorMessage = [System.Collections.ArrayList]@()
$this.UnderlyingScheduleDisabled = $false
}
[void] UpdateDynamicAzureQueriesStatus(
[bool]$hasDynamicAzureQueries,
[bool]$allDynamicAzureQueriesSuccessfullyResolved,
[bool]$allDynamicAzureQueriesSuccessfullyAssigned)
{
<#
.SYNOPSIS
Updates status of dynamic azure queries in regards to software update configuration.
.DESCRIPTION
This function will update dynamic azure queries data in regards to software update configuration.
.PARAMETER hasDynamicAzureQueries
Whether software update configuration has dynamic azure queries or not.
.PARAMETER allDynamicAzureQueriesSuccessfullyResolved
Whether all dynamic azure queries successfully resolved against ARG to get the machines or not.
.PARAMETER allDynamicAzureQueriesSuccessfullyAssigned
Whether all dynamic azure queries have successful dynamc scoping assignments or not.
#>
$this.DynamicAzureQueriesStatus.HasDynamicAzureQueries = $hasDynamicAzureQueries
$this.DynamicAzureQueriesStatus.AllDynamicAzureQueriesSuccessfullyResolved = $allDynamicAzureQueriesSuccessfullyResolved
$this.DynamicAzureQueriesStatus.AllDynamicAzureQueriesSuccessfullyAssigned = $allDynamicAzureQueriesSuccessfullyAssigned
}
[void] UpdatePrePostStatus(
[bool]$hasPreTasks,
[bool]$preTasksAssignedSuccessfully,
[bool]$hasPostTasks,
[bool]$postTasksAssignedSuccessfully)
{
<#
.SYNOPSIS
Updates status of pre and post tasks in regards to software update configuration.
.DESCRIPTION
This function will update status of pre and post tasks in regards to software update configuration.
.PARAMETER hasPreTasks
Whether software update configuration has pre tasks.
.PARAMETER preTasksAssignedSuccessfully
Whether pre tasks successfully assigned to maintenance configuration.
.PARAMETER hasPostTasks
Whether software update configuration has post tasks.
.PARAMETER postTasksAssignedSuccessfully
Whether post tasks successfully assigned to maintenance configuration.
#>
$this.PrePostStatus.HasPreTasks = $hasPreTasks
$this.PrePostStatus.PreTasksAssignedSuccessfully = $preTasksAssignedSuccessfully
$this.PrePostStatus.HasPostTasks = $hasPostTasks
$this.PrePostStatus.PostTasksAssignedSuccessfully = $postTasksAssignedSuccessfully
}
[void] UpdateMachineStatusForSoftwareUpdateConfiguration(
[String]$resourceId,
[bool]$isConfigAssignmentRequired,
[bool]$isConfigAssignmentSuccessful,
[bool]$isMachineResolvedThroughAzureDynamicQuery,
[String]$errorCode,
[String]$errorMessage)
{
<#
.SYNOPSIS
Updates status of machines in regards to software update configuration.
.DESCRIPTION
This function will add/edit machine readiness data in regards to software update configuration.
.PARAMETER resourceId
ARM resourceId of the machine.
.PARAMETER isConfigAssignmentRequired
Machine attached to schedule or picked up dynamically at run time.
.PARAMETER isConfigAssignmentSuccessful
Machine is attached to maintenance configuration or not.
.PARAMETER isMachineResolvedThroughAzureDynamicQuery
Machine is resolved through dynamic query of SUC or not.
.PARAMETER errorCode
Error code for machine association status with maintenance configuration.
.PARAMETER errorMessage
Error message for machine association status with maintenance configuration.
#>
if ($this.MachinesReadinessDataForSoftwareUpdateConfiguration.ContainsKey($resourceId))
{
$this.MachinesReadinessDataForSoftwareUpdateConfiguration[$resourceId].IsConfigAssignmentRequired = $isConfigAssignmentRequired
$this.MachinesReadinessDataForSoftwareUpdateConfiguration[$resourceId].IsConfigAssignmentSuccessful = $isConfigAssignmentSuccessful
$this.MachinesReadinessDataForSoftwareUpdateConfiguration[$resourceId].IsMachineResolvedThroughAzureDynamicQuery = $isMachineResolvedThroughAzureDynamicQuery
$this.MachinesReadinessDataForSoftwareUpdateConfiguration[$resourceId].ErrorCode = $errorCode
$this.MachinesReadinessDataForSoftwareUpdateConfiguration[$resourceId].ErrorMessage = $errorMessage
}
else
{
$machineReadinessDataForSoftwareUpdateConfiguration = [MachineReadinessDataForSoftwareUpdateConfiguration]::new()
$machineReadinessDataForSoftwareUpdateConfiguration.ResourceId = $resourceId
$machineReadinessDataForSoftwareUpdateConfiguration.IsConfigAssignmentRequired = $isConfigAssignmentRequired
$machineReadinessDataForSoftwareUpdateConfiguration.IsConfigAssignmentSuccessful = $isConfigAssignmentSuccessful
$machineReadinessDataForSoftwareUpdateConfiguration.IsMachineResolvedThroughAzureDynamicQuery = $isMachineResolvedThroughAzureDynamicQuery
$machineReadinessDataForSoftwareUpdateConfiguration.ErrorCode = $errorCode
$machineReadinessDataForSoftwareUpdateConfiguration.ErrorMessage = $errorMessage
$this.MachinesReadinessDataForSoftwareUpdateConfiguration[$resourceId] = $machineReadinessDataForSoftwareUpdateConfiguration
}
}
}
#Max depth of payload.
$MaxDepth = 5
# Beginning of Payloads.
$ResourceGroupPayload = @"
{
"location": null
}
"@
$WindowsAssessmentMode = @"
{
"properties": {
"osProfile": {
"windowsConfiguration": {
"patchSettings": {
"assessmentMode": "AutomaticByPlatform"
}
}
}
}
}
"@
$LinuxAssessmentMode = @"
{
"properties": {
"osProfile": {
"linuxConfiguration": {
"patchSettings": {
"assessmentMode": "AutomaticByPlatform"
}
}
}
}
}
"@
$WindowsPatchSettingsOnAzure = @"
{
"properties": {
"osProfile": {
"windowsConfiguration": {
"patchSettings": {
"assessmentMode": "AutomaticByPlatform",
"patchMode": "AutomaticByPlatform",
"automaticByPlatformSettings": {
"bypassPlatformSafetyChecksOnUserSchedule": true
}
}
}
}
}
}
"@
$LinuxPatchSettingsOnAzure = @"
{
"properties": {
"osProfile": {
"linuxConfiguration": {
"patchSettings": {
"assessmentMode": "AutomaticByPlatform",
"patchMode": "AutomaticByPlatform",
"automaticByPlatformSettings": {
"bypassPlatformSafetyChecksOnUserSchedule": true
}
}
}
}
}
}
"@
$MaintenanceConfigurationSettings = @"
{
"location": "",
"properties": {
"namespace": null,
"extensionProperties": {
"InGuestPatchMode" : "User"
},
"maintenanceScope": "InGuestPatch",
"maintenanceWindow": {
"startDateTime": null,
"expirationDateTime": null,
"duration": null,
"timeZone": null,
"recurEvery": null
},
"visibility": "Custom",
"installPatches": {
"rebootSetting": null,
"windowsParameters": {
"classificationsToInclude": [
],
"kbNumbersToInclude": [
],
"kbNumbersToExclude": [
]
},
"linuxParameters": {
"classificationsToInclude": [
],
"packageNameMasksToInclude": [
],
"packageNameMasksToExclude": [
]
}
}
}
}
"@
$MaintenanceConfigurationAssignmentSettings = @"
{
"properties":
{
"maintenanceConfigurationId": null
},
"location": null
}
"@
$MaintenanceConfigurationDynamicScopingSettings = @"
{
"location": null,
"properties": {
"maintenanceConfigurationId": null,
"filter": {
"tagSettings": {
"tags": {
},
"filterOperator": "All"
},
"resourceTypes": [
"Microsoft.Compute/virtualMachines"
],
"locations": [
],
"resourceGroups": [
],
"osTypes": [
]
}
}
}
"@
$DisableAutomationSchedule = @"
{
"properties":
{
"isEnabled": false
}
}
"@
$CreateWebhook = @"
{
"name": null,
"properties": {
"isEnabled": true,
"uri": null,
"expiryTime": null,
"runbook": {
"name": null
},
"parameters":{
}
}
}
"@
$CreateSystemTopic = @"
{
"name": null,
"type": "Microsoft.EventGrid/systemTopics",
"location": null,
"properties": {
"source": null,
"topicType": "Microsoft.Maintenance.MaintenanceConfigurations"
}
}
"@
$CreatePreMaintenanceEventSubscription = @"
{
"name": null,
"properties": {
"topic": null,
"destination": {
"endpointType": "WebHook",
"properties": {
"endpointUrl": null,
"maxEventsPerBatch": 1,
"preferredBatchSizeInKilobytes": 64
}
},
"filter": {
"includedEventTypes": [
"Microsoft.Maintenance.PreMaintenanceEvent"
],
"advancedFilters": [],
"enableAdvancedFilteringOnArrays": true
},
"labels": [],
"eventDeliverySchema": "EventGridSchema"
}
}
"@
$CreatePostMaintenanceEventSubscription = @"
{
"name": null,
"properties": {
"topic": null,
"destination": {
"endpointType": "WebHook",
"properties": {
"endpointUrl": null,
"maxEventsPerBatch": 1,
"preferredBatchSizeInKilobytes": 64
}
},
"filter": {
"includedEventTypes": [
"Microsoft.Maintenance.PostMaintenanceEvent"
],
"advancedFilters": [],
"enableAdvancedFilteringOnArrays": true
},
"labels": [],
"eventDeliverySchema": "EventGridSchema"
}
}
"@
# End of Payloads.
$MachinesOnboaredToAutomationUpdateManagementQuery = 'Heartbeat | where Solutions contains "updates" | distinct Computer, ResourceId, ResourceType, OSType'
$Global:Machines = @{}
$Global:AutomationAccountRegion = $null
$Global:JobSchedules = @{}
$Global:SoftwareUpdateConfigurationsResourceIDs = @{}
$Global:MachinesRetrievedFromLogAnalyticsWorkspaceWithUpdatesSolution = 0
$Global:MachinesRetrievedFromAzureDynamicQueriesWhichAreNotOnboardedToAutomationUpdateManagement = 0
$Global:ResourceGroupForMaintenanceConfigurations = $null
function Write-Telemetry
{
<#
.Synopsis
Writes telemetry to the job logs.
Telemetry levels can be "Informational", "Warning", "Error" or "Verbose".
.PARAMETER Message
Log message to be written.
.PARAMETER Level
Log level.
.EXAMPLE
Write-Telemetry -Message Message -Level Level.
#>
param(
[Parameter(Mandatory = $true, Position = 1)]
[String]$Message,
[Parameter(Mandatory = $false, Position = 2)]
[ValidateScript({ $_ -in $TelemetryLevels })]
[String]$Level = $Informational
)
if ($Level -eq $Warning)
{
Write-Warning $Message
}
elseif ($Level -eq $ErrorLvl)
{
Write-Error $Message
}
else
{
Write-Verbose $Message -Verbose
}
}
function Parse-ArmId
{
<#
.SYNOPSIS
Parses ARM resource id.
.DESCRIPTION
This function parses ARM id to return subscription, resource group, resource name, etc.
.PARAMETER ResourceId
ARM resourceId of the machine.
.EXAMPLE
Parse-ArmId -ResourceId "/subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Automation/automationAccounts/{aaName}"
#>
param(
[Parameter(Mandatory = $true, Position = 1)]
[String]$ResourceId
)
$parts = $ResourceId.Split("/")
return @{
Subscription = $parts[2]
ResourceGroup = $parts[4]
ResourceProvider = $parts[6]
ResourceType = $parts[7]
ResourceName = $parts[8]
}
}
function Invoke-RetryWithOutput
{
<#
.SYNOPSIS
Generic retry logic.
.DESCRIPTION
This command will perform the action specified until the action generates no errors, unless the retry limit has been reached.
.PARAMETER Command
Accepts an Action object.
You can create a script block by enclosing your script within curly braces.
.PARAMETER Retry
Number of retries to attempt.
.PARAMETER Delay
The maximum delay (in seconds) between each attempt. The default is 5 seconds.
.EXAMPLE
$cmd = { If ((Get-Date) -lt (Get-Date -Second 59)) { Get-Object foo } Else { Write-Host 'ok' } }
Invoke-RetryWithOutput -Command $cmd -Retry 61
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[ScriptBlock]$Command,
[Parameter(Mandatory = $false, Position = 2)]
[ValidateRange(0, [UInt32]::MaxValue)]
[UInt32]$Retry = 3,
[Parameter(Mandatory = $false, Position = 3)]
[ValidateRange(0, [UInt32]::MaxValue)]
[UInt32]$Delay = 5
)
$ErrorActionPreferenceToRestore = $ErrorActionPreference
$ErrorActionPreference = "Stop"
for ($i = 0; $i -lt $Retry; $i++)
{
$exceptionMessage = ""
try
{
Write-Telemetry -Message ("[Debug]Command [{0}] started. Retry: {1}." -f $Command, ($i + 1) + $ForwardSlashSeparator + $Retry)
$output = Invoke-Command $Command
Write-Telemetry -Message ("[Debug]Command [{0}] succeeded." -f $Command)
$ErrorActionPreference = $ErrorActionPreferenceToRestore
return $output
}
catch [Exception]
{
$exceptionMessage = $_.Exception.Message
if ($Global:Error.Count -gt 0)
{
$Global:Error.RemoveAt(0)
}
if ($i -eq ($Retry - 1))
{
$message = ("[Debug]Command [{0}] failed even after [{1}] retries. Exception message:{2}." -f $command, $Retry, $exceptionMessage)
Write-Telemetry -Message $message -Level $ErrorLvl
$ErrorActionPreference = $ErrorActionPreferenceToRestore
throw $message
}
$exponential = [math]::Pow(2, ($i + 1))
$retryDelaySeconds = ($exponential - 1) * $Delay # Exponential Backoff Max == (2^n)-1
Write-Telemetry -Message ("[Debug]Command [{0}] failed. Retrying in {1} seconds, exception message:{2}." -f $command, $retryDelaySeconds, $exceptionMessage) -Level $Warning
Start-Sleep -Seconds $retryDelaySeconds
}
}
}
function Invoke-AzRestApiWithRetry
{
<#
.SYNOPSIS
Wrapper around Invoke-AzRestMethod.
.DESCRIPTION
This function calls Invoke-AzRestMethod with retries.
.PARAMETER Params
Parameters to the cmdlet.
.PARAMETER Payload
Payload.
.PARAMETER Retry
Number of retries to attempt.
.PARAMETER Delay
The maximum delay (in seconds) between each attempt. The default is 5 seconds.
.EXAMPLE
Invoke-AzRestApiWithRetry -Params @{SubscriptionId = "xxxx" ResourceGroup = "rgName" ResourceName = "resourceName" ResourceProvider = "Microsoft.Compute" ResourceType = "virtualMachines"} -Payload "{'location': 'westeurope'}"
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[System.Collections.Hashtable]$Params,
[Parameter(Mandatory = $false, Position = 2)]
[Object]$Payload = $null,
[Parameter(Mandatory = $false, Position = 3)]
[ValidateRange(0, [UInt32]::MaxValue)]
[UInt32]$Retry = 3,
[Parameter(Mandatory = $false, Position = 4)]
[ValidateRange(0, [UInt32]::MaxValue)]
[UInt32]$Delay = 5
)
if ($Payload)
{
[void]$Params.Add('Payload', $Payload)
}
$retriableErrorCodes = @(409, 429)
for ($i = 0; $i -lt $Retry; $i++)
{
$exceptionMessage = ""
$paramsString = $Params | ConvertTo-Json -Compress -Depth $MaxDepth | ConvertFrom-Json
try
{
Write-Telemetry -Message ("[Debug]Invoke-AzRestMethod started with params [{0}]. Retry: {1}." -f $paramsString, ($i+1) + $ForwardSlashSeparator + $Retry)
$output = Invoke-AzRestMethod @Params -ErrorAction Stop
$outputString = $output | ConvertTo-Json -Compress -Depth $MaxDepth | ConvertFrom-Json
if ($retriableErrorCodes.Contains($output.StatusCode) -or $output.StatusCode -ge 500)
{
if ($i -eq ($Retry - 1))
{
$message = ("[Debug]Invoke-AzRestMethod with params [{0}] failed even after [{1}] retries. Failure reason:{2}." -f $paramsString, $Retry, $outputString)
Write-Telemetry -Message $message -Level $ErrorLvl
return Process-ApiResponse -Response $output
}
$exponential = [math]::Pow(2, ($i+1))
$retryDelaySeconds = ($exponential - 1) * $Delay # Exponential Backoff Max == (2^n)-1
Write-Telemetry -Message ("[Debug]Invoke-AzRestMethod with params [{0}] failed with retriable error code. Retrying in {1} seconds, Failure reason:{2}." -f $paramsString, $retryDelaySeconds, $outputString) -Level $Warning
Start-Sleep -Seconds $retryDelaySeconds
}
else
{
Write-Telemetry -Message ("[Debug]Invoke-AzRestMethod with params [{0}] succeeded. Output: [{1}]." -f $paramsString, $outputString)
return Process-ApiResponse -Response $output
}
}
catch [Exception]
{
$exceptionMessage = $_.Exception.Message
Write-Telemetry -Message ("[Debug]Invoke-AzRestMethod with params [{0}] failed with an unhandled exception: {1}." -f $paramsString, $exceptionMessage) -Level $ErrorLvl
throw
}
}
}
function Invoke-ArmApi-WithPath
{
<#
.SYNOPSIS
The function prepares payload for Invoke-AzRestMethod
.DESCRIPTION
This function prepares payload for Invoke-AzRestMethod.
.PARAMETER Path
ARM API path.
.PARAMETER ApiVersion
API version.
.PARAMETER Method
HTTP method.
.PARAMETER Payload
Paylod for API call.
.EXAMPLE
Invoke-ArmApi-WithPath -Path "/subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Compute/virtualMachines/{vmName}/start" -ApiVersion "2023-03-01" -method "PATCH" -Payload "{'location': 'westeurope'}"
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[String]$Path,
[Parameter(Mandatory = $true, Position = 2)]
[String]$ApiVersion,
[Parameter(Mandatory = $true, Position = 3)]
[ValidateScript({ $_ -in $HttpMethods })]
[String]$Method,
[Parameter(Mandatory = $false, Position =4)]
[Object]$Payload = $null
)