-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMigrationPrerequisites.ps1
1157 lines (969 loc) · 47.2 KB
/
MigrationPrerequisites.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
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 will carry out the prerequisites required for migration of machines and software update configurations from Azure Automation Update Management to Azure Update Manager.
.DESCRIPTION
This script will do the following:
1. Retrieve all machines onboarded to Azure Automation Update Management under this automation account from linked Log Analytics Workspace.
2. Update the Az.Modules for the automation account.
3. Creates an automation variable with name AutomationAccountAzureEnvironment which will store the Azure Cloud Environment to which Automation Account belongs.
4. Create user managed identity in the same subscription and resource group as the automation account.
5. Associate the user managed identity to the automation account.
6. Assign required roles to the user managed identity created.
The executor of the script should have Microsoft.Authorization/roleAssignments/write action such as Role Based Access Control Administrator on the scopes on which access will be granted to user managed identity.
The script will register the automation subscription, subscriptions to which machines belong and subscriptions in dynamic Azure queries to Microsoft.Maintenance and hence executor of the script should have Contributor/Owner access to all those subscriptions.
The script will register the automation subscription to Microsoft.EventGrid and hence executor of the script should have Contributor/Owner access to the subscription.
.PARAMETER AutomationAccountResourceId
Mandatory
Automation Account Resource Id.
.PARAMETER AutomationAccountAzureEnvironment
Mandatory
Azure Cloud Environment to which Automation Account belongs.
Accepted values are AzureCloud, AzureUSGovernment, AzureChinaCloud.
.EXAMPLE
MigrationPrerequisites -AutomationAccountResourceId "/subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Automation/automationAccounts/{aaName}" -AutomationAccountAzureEnvironment "AzureCloud"
.OUTPUTS
The user managed identity with required role assignments.
#>
param (
[Parameter(Mandatory = $true)]
[String]$AutomationAccountResourceId,
[Parameter(Mandatory = $true)]
[String]$AutomationAccountAzureEnvironment = "AzureCloud"
)
# Telemetry level.
$Debug = "Debug"
$Verbose = "Verbose"
$Informational = "Informational"
$Warning = "Warning"
$ErrorLvl = "Error"
$Succeeded = "Succeeded"
$Failed = "Failed"
# ARM resource types.
$VMResourceType = "virtualMachines";
$ArcVMResourceType = "machines";
# API versions.
$AutomationApiVersion = "2023-11-01"; # Azure Automation: https://learn.microsoft.com/rest/api/automation/automation-account
$SoftwareUpdateConfigurationApiVersion = "2023-11-01"; # Azure Software Update Configurations: https://learn.microsoft.com/rest/api/automation/softwareupdateconfigurations
$UserManagedIdentityApiVersion = "2023-01-31"; # Managed Identities: https://learn.microsoft.com/rest/api/managedidentity/user-assigned-identities
$AzureRoleAssignmentApiVersion = "2022-04-01"; # Azure Role Assignments: https://learn.microsoft.com/rest/api/authorization/role-assignments
$SolutionsApiVersion = "2015-11-01-preview"; # Solutions (Operations Management): https://learn.microsoft.com/azure/templates/microsoft.operationsmanagement/change-log/summary
$RegisterResourceProviderApiVersion = "2022-12-01"; # Resource Provider Registration: https://learn.microsoft.com/rest/api/resources/providers/register
$AutomationVariableApiVersion = "2023-11-01"; # Azure Automation Variables: https://learn.microsoft.com/rest/api/automation/variable
# HTTP methods.
$GET = "GET"
$PATCH = "PATCH"
$PUT = "PUT"
$POST = "POST"
# ARM endpoints.
$LinkedWorkspacePath = "{0}/linkedWorkspace"
$SoftwareUpdateConfigurationsPath = "{0}/softwareUpdateConfigurations?`$skip={1}"
$SolutionsWithWorkspaceFilterPath = "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.OperationsManagement/solutions?`$filter=properties/workspaceResourceId%20eq%20'{2}'"
$UserManagedIdentityPath = "subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{2}"
$AzureRoleDefinitionPath = "/providers/Microsoft.Authorization/roleDefinitions/{0}"
$AzureRoleAssignmentPath = "{0}/providers/Microsoft.Authorization/roleAssignments/{1}"
$MaintenanceResourceProviderRegistrationPath = "/subscriptions/{0}/providers/Microsoft.Maintenance/register"
$EventGridResourceProviderRegistrationPath = "/subscriptions/{0}/providers/Microsoft.EventGrid/register"
$AutomationVariablePath = "{0}/variables/AutomationAccountAzureEnvironment"
# Role Definition IDs.
$AzureConnectedMachineOnboardingRole = "b64e21ea-ac4e-4cdf-9dc9-5b892992bee7"
$VirtualMachineContributorRole = "9980e02c-c2be-4d73-94e8-173b1dc7cf3c"
$LogAnalyticsContributorRole = "92aaf0da-9dab-42b6-94a3-d43ce8d16293"
$LogAnalyticsReaderRole = "73c42c96-874c-492b-b04d-ab87d138a893"
$AutomationOperatorRole = "d3881f73-407a-4167-8283-e981cbba0404"
$ScheduledPatchingContributorRole = "cd08ab90-6b14-449c-ad9a-8f8e549482c6"
$ContributorRole = "b24988ac-6180-42a0-ab88-20f7382dd24c"
# Validation values.
$TelemetryLevels = @($Debug, $Verbose, $Informational, $Warning, $ErrorLvl)
$HttpMethods = @($GET, $PATCH, $POST, $PUT)
#Max depth of payload.
$MaxDepth = 5
# Beginning of Payloads.
$AssignUserManagedIdentityToAutomationAccountPayload = @"
{
"identity": {
"type": "",
"userAssignedIdentities": {
}
}
}
"@
$UserManagedIdentityCreationPayload = @"
{
"location": "",
"tags": {
}
}
"@
$UpdateAzModulesPayload = @"
{
"properties": {
"RuntimeConfiguration": {
"powershell": {
"builtinModules": {
"Az": "8.0.0"
}
}
}
}
}
"@
$RoleAssignmentPayload = @"
{
"Id": "",
"Properties": {
"PrincipalId": "",
"PrincipalType": "ServicePrincipal",
"RoleDefinitionId": "",
"Scope": ""
}
}
"@
$AutomationVariablePayload = @"
{
"name": "",
"properties": {
"value": "",
"description": "Azure Cloud Environment for the Automation Account",
"isEncrypted": false
}
}
"@
# End of Payloads.
$MachinesOnboaredToAutomationUpdateManagementQuery = 'Heartbeat | where Solutions contains "updates" | distinct Computer, ResourceId, ResourceType, OSType'
$Global:Machines = [System.Collections.ArrayList]@()
$Global:AutomationAccountRegion = $null
$Global:UserManagedIdentityResourceId = $null
$Global:UserManagedIdentityPrincipalId = $null
$Global:SoftwareUpdateConfigurationsResourceIDs = @{ }
$Global:AzureDynamicQueriesScope = @{ }
$Global:SubscriptionsToRegisterToMaintenanceResourceProvider = @{ }
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 = @(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
)
$PathWithVersion = "{0}?api-version={1}"
if ($Path.Contains("?")) {
$PathWithVersion = "{0}&api-version={1}"
}
$Uri = ($PathWithVersion -f $Path, $ApiVersion)
$Params = @{
Path = $Uri
Method = $Method
}
return Invoke-AzRestApiWithRetry -Params $Params -Payload $Payload
}
function Process-ApiResponse {
<#
.SYNOPSIS
Process API response and returns data.
.PARAMETER Response
Response object.
.EXAMPLE
Process-ApiResponse -Response {"StatusCode": 200, "Content": "{\"properties\": {\"location\": \"westeurope\"}}" }
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[Object]$Response
)
$content = $null
if ($Response.Content) {
$content = ConvertFrom-Json $Response.Content
}
if ($Response.StatusCode -eq 200) {
return @{
Status = $Succeeded
Response = $content
ErrorCode = [String]::Empty
ErrorMessage = [String]::Empty
}
}
else {
$errorCode = $Unknown
$errorMessage = $Unknown
if ($content.error) {
$errorCode = ("{0}/{1}" -f $Response.StatusCode, $content.error.code)
$errorMessage = $content.error.message
}
return @{
Status = $Failed
Response = $content
ErrorCode = $errorCode
ErrorMessage = $errorMessage
}
}
}
function Get-MachinesFromLogAnalytics {
<#
.SYNOPSIS
Gets machines onboarded to updates solution from Log Analytics Workspace.
.DESCRIPTION
This command will return machines onboarded to UM from LA workspace.
.PARAMETER ResourceId
Resource Id.
.EXAMPLE
Get-MachinesFromLogAnalytics -ResourceId "/subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Automation/automationAccounts/{aaName}"
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[String]$ResourceId
)
$armComponents = Parse-ArmId -ResourceId $ResourceId
$script = {
Set-AzContext -Subscription $armComponents.Subscription
$Workspace = Get-AzOperationalInsightsWorkspace -ResourceGroupName $armComponents.ResourceGroup -Name $armComponents.ResourceName
$QueryResults = Invoke-AzOperationalInsightsQuery -WorkspaceId $Workspace.CustomerId -Query $MachinesOnboaredToAutomationUpdateManagementQuery -ErrorAction Stop
return $QueryResults
}
$output = Invoke-RetryWithOutput -command $script
return $output
}
function Populate-AllMachinesOnboardedToUpdateManagement {
<#
.SYNOPSIS
Gets all machines onboarded to Update Management under this automation account.
.DESCRIPTION
This function gets all machines onboarded to Automation Update Management under this automation account using Log Analytics Workspace.
.PARAMETER AutomationAccountResourceId
Automation account resource id.
.EXAMPLE
Populate-AllMachinesOnboardedToUpdateManagement -AutomationAccountResourceId "/subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Automation/automationAccounts/{aaName}"
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[String]$AutomationAccountResourceId
)
try {
$linkedWorkspace = Invoke-ArmApi-WithPath -Path ($LinkedWorkspacePath -f $AutomationAccountResourceId) -ApiVersion $AutomationApiVersion -Method $GET
$laResults = Get-MachinesFromLogAnalytics -ResourceId $linkedWorkspace.Response.Id
if ($laResults.Results.Count -eq 0 -and $null -eq $laResults.Error) {
Write-Telemetry -Message ("Zero machines retrieved from Log Analytics Workspace. If machines were recently onboarded, please wait for few minutes for machines to start reporting to Log Analytics Workspace") -Level $ErrorLvl
throw
}
elseif ($laResults.Results.Count -gt 0 -or @($laResults.Results).Count -gt 0) {
Write-Telemetry -Message ("Retrieved machines from Log Analytics Workspace.")
foreach ($record in $laResults.Results) {
if ($record.ResourceType -eq $ArcVMResourceType -or $record.ResourceType -eq $VMResourceType) {
[void]$Global:Machines.Add($record.ResourceId)
}
}
}
else {
Write-Telemetry -Message ("Failed to get machines from Log Analytics Workspace with error {0}." -f $laResults.Error) -Level $ErrorLvl
throw
}
}
catch [Exception] {
Write-Telemetry -Message ("Unhandled exception {0}." -f , $_.Exception.Message) -Level $ErrorLvl
throw
}
}
function Create-UserManagedIdentity {
<#
.SYNOPSIS
Creates user managed Identity.
.DESCRIPTION
This function will create user managed Identity in the same subscription and resource group as the automation account.
.PARAMETER AutomationAccountResourceId
Automation account resource id.
.EXAMPLE
Create-UserManagedIdentity -AutomationAccountResourceId "/subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Automation/automationAccounts/{aaName}"
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[String]$AutomationAccountResourceId
)
try {
$response = Invoke-ArmApi-WithPath -Path $AutomationAccountResourceId -ApiVersion $AutomationApiVersion -Method $GET
$Global:AutomationAccountRegion = $response.Response.location
$parts = $AutomationAccountResourceId.Split("/")
$userManagedIdentityPayload = ConvertFrom-Json $UserManagedIdentityCreationPayload
$userManagedIdentityPayload.location = $Global:AutomationAccountRegion
$userManagedIdentityPayload = ConvertTo-Json $userManagedIdentityPayload -Depth $MaxDepth
$response = Invoke-ArmApi-WithPath -Path ($UserManagedIdentityPath -f $parts[2], $parts[4], $parts[8] + "_AUMMig_uMSI") -ApiVersion $UserManagedIdentityApiVersion -Method $PUT -Payload $userManagedIdentityPayload
if ($null -eq $response.Response.id) {
Write-Telemetry -Message ("Failed to create user managed identity with error code {0} and error message {1}." -f $response.ErrorCode, $response.ErrorMessage) -Level $ErrorLvl
throw
}
else {
Write-Telemetry -Message ("Successfully created user managed identity with id {0}." -f , $response.Response.id)
$Global:UserManagedIdentityResourceId = $response.Response.id
$Global:UserManagedIdentityPrincipalId = $response.Response.properties.principalId
}
}
catch [Exception] {
Write-Telemetry -Message ("Unhandled Exception {0}." -f $_.Exception.Message) -Level $ErrorLvl
throw
}
}
function Register-EventGridResourceProviderToSubscription {
<#
.SYNOPSIS
Register subscription with Microsoft.EventGrid Resource Provider.
.DESCRIPTION
This function will register subscription with Microsoft.EventGrid Resource Provider.
.PARAMETER ResourceId
Resource id.
.EXAMPLE
Register-EventGridResourceProviderToSubscription ResourceId "{resId}"
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[String]$ResourceId
)
try {
# Register the subscription to which automation account belongs to Microsoft.EventGrid.
$parts = $ResourceId.Split("/")
$response = Invoke-ArmApi-WithPath -Path ($EventGridResourceProviderRegistrationPath -f $parts[2]) -ApiVersion $RegisterResourceProviderApiVersion -Method $POST
if ($null -eq $response.Response.id) {
Write-Telemetry -Message ("Failed to register resource provider Microsoft.EventGrid with subscription {0} with error code {1} and error message {2}." -f $parts[2], $response.ErrorCode, $response.ErrorMessage) -Level $ErrorLvl
}
else {
Write-Telemetry -Message ("Successfully registered resource provider Microsoft.EventGrid with subscription {0}." -f $parts[2])
}
}
catch [Exception] {
Write-Telemetry -Message ("Unhandled Exception {0} while registering subscription {1} to Microsoft.EventGrid." -f $_.Exception.Message, $parts[2]) -Level $ErrorLvl
throw
}
}
function Register-MaintenanceResourceProviderToSubscription {
<#
.SYNOPSIS
Register subscription with Microsoft.Maintenance Resource Provider.
.DESCRIPTION
This function will register subscription with Microsoft.Maintenance Resource Provider.
.PARAMETER ResourceId
Resource id.
.EXAMPLE
Register-MaintenanceResourceProviderToSubscription ResourceId "{resId}"
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[String]$ResourceId
)
try {
# Register the subscription to which resource belongs to Microsoft.Maintenance.
$parts = $ResourceId.Split("/")
if (!$Global:SubscriptionsToRegisterToMaintenanceResourceProvider.ContainsKey($parts[2])) {
$response = Invoke-ArmApi-WithPath -Path ($MaintenanceResourceProviderRegistrationPath -f $parts[2]) -ApiVersion $RegisterResourceProviderApiVersion -Method $POST
if ($null -eq $response.Response.id) {
Write-Telemetry -Message ("Failed to register resource provider Microsoft.Maintenance with subscription {0} with error code {1} and error message {2}." -f $parts[2], $response.ErrorCode, $response.ErrorMessage) -Level $ErrorLvl
}
else {
Write-Telemetry -Message ("Successfully registered resource provider Microsoft.Maintenance with subscription {0}." -f $parts[2])
$Global:SubscriptionsToRegisterToMaintenanceResourceProvider[$parts[2]] = $true
}
}
}
catch [Exception] {
Write-Telemetry -Message ("Unhandled Exception {0} while registering subscription {1} to Microsoft.Maintenance." -f $_.Exception.Message, $parts[2]) -Level $ErrorLvl
throw
}
}
function Add-UserManagedIdentityToAutomationAccount {
<#
.SYNOPSIS
Adds user managed Identity to the automation account.
.DESCRIPTION
This function will add user managed Identity to the automation account.
.PARAMETER AutomationAccountResourceId
Automation account resource id.
.EXAMPLE
Add-UserManagedIdentityToAutomationAccount -AutomationAccountResourceId "/subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Automation/automationAccounts/{aaName}"
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[String]$AutomationAccountResourceId
)
try {
$response = Invoke-ArmApi-WithPath -Path $AutomationAccountResourceId -ApiVersion $AutomationApiVersion -Method $GET
$userManagedIdentityPayload = ConvertFrom-Json $AssignUserManagedIdentityToAutomationAccountPayload
# Honour the current identity settings for the automation account.
if ($response.Response.identity.type -Match "userassigned") {
$userManagedIdentityPayload.identity.type = $response.Response.identity.type
}
elseif ($response.Response.identity.type -Match "systemassigned") {
$userManagedIdentityPayload.identity.type = "systemassigned,userassigned"
}
else {
$userManagedIdentityPayload.identity.type = "userassigned"
}
# Existing user managed identities should be kept as it is.
$userManagedIdentities = @{ }
foreach ($property in $response.Response.identity.userAssignedIdentities.psobject.properties) {
[void]$userManagedIdentities.Add($property.Name, @{ })
}
# Add the user managed identity for migration.
if (!$userManagedIdentities.ContainsKey($Global:UserManagedIdentityResourceId)) {
[void]$userManagedIdentities.Add($Global:UserManagedIdentityResourceId, @{ })
}
$userManagedIdentityPayload.identity.userAssignedIdentities = $userManagedIdentities
$userManagedIdentityPayload = ConvertTo-Json $userManagedIdentityPayload -Depth $MaxDepth
$response = Invoke-ArmApi-WithPath -Path $AutomationAccountResourceId -ApiVersion $AutomationApiVersion -Method $PATCH -Payload $userManagedIdentityPayload
if ($response.Status -eq $Failed) {
Write-Telemetry -Message ("Failed to add user managed identity with error code {0} and error message {1}." -f $response.ErrorCode, $response.ErrorMessage) -Level $ErrorLvl
throw
}
else {
Write-Telemetry -Message ("Successfully added user managed identity {0} to automation account {1}." -f , $Global:UserManagedIdentityResourceId, $Global:AutomationAccountRegion)
}
}
catch [Exception] {
Write-Telemetry -Message ("Unhandled Exception {0}." -f $_.Exception.Message) -Level $ErrorLvl
throw
}
}
function Update-AzModules {
<#
.SYNOPSIS
Updates Az Modules for the automation account.
.DESCRIPTION
This function will update Az modules for the automation account. Ensure to update any runbooks in the automation account that are not compatible post this update.
.PARAMETER AutomationAccountResourceId
Automation account resource id.
.EXAMPLE
Update-AzModules -AutomationAccountResourceId "/subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Automation/automationAccounts/{aaName}"
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[String]$AutomationAccountResourceId
)
try {
$response = Invoke-ArmApi-WithPath -Path $AutomationAccountResourceId -ApiVersion $AutomationApiVersion -Method $PATCH -Payload $UpdateAzModulesPayload
if ($response.Status -eq $Failed) {
Write-Telemetry -Message ("Failed to update Az modules with error code {0} and error message {1}." -f $response.ErrorCode, $response.ErrorMessage) -Level $ErrorLvl
}
else {
Write-Telemetry -Message ("Successfully updated Az modules." -f , $Global:UserManagedIdentityResourceId, $Global:AutomationAccountRegion)
}
}
catch [Exception] {
Write-Telemetry -Message ("Unhandled Exception {0}." -f $_.Exception.Message) -Level $ErrorLvl
throw
}
}
function Add-AutomationAccountAzureEnvironmentVariable {
<#
.SYNOPSIS
Adds Azure environment variable for the automation account.
.DESCRIPTION
This function will add Azure environment variable for the automation account.
.PARAMETER AutomationAccountResourceId
Automation account resource id.
.PARAMETER AutomationAccountAzureEnvironment
Azure Cloud to which automation account belongs to.
.EXAMPLE
Add-AutomationAccountAzureEnvironmentVariable -AutomationAccountResourceId "/subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Automation/automationAccounts/{aaName}" -AutomationAccountAzureEnvironment "AzureCloud"
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[String]$AutomationAccountResourceId,
[Parameter(Mandatory = $true, Position = 2)]
[String]$AutomationAccountAzureEnvironment
)
try {
$payload = ConvertFrom-Json $AutomationVariablePayload
$payload.name = "AutomationAccountAzureEnvironment"
$payload.properties.value = """$AutomationAccountAzureEnvironment"""
$payload = ConvertTo-Json $payload -Depth $MaxDepth
$response = Invoke-ArmApi-WithPath -Path ($AutomationVariablePath -f $AutomationAccountResourceId) -ApiVersion $AutomationVariableApiVersion -Method $PUT -Payload $payload
if ($null -eq $response.Response.Id -and $response.Status -eq $Failed) {
Write-Telemetry -Message ("Failed to add variable with error code {0} and error message {1}." -f $response.ErrorCode, $response.ErrorMessage) -Level $ErrorLvl
}
else {
Write-Telemetry -Message ("Successfully added variable AutomationAccountAzureEnvironment to automation account.")
}
}
catch [Exception] {
Write-Telemetry -Message ("Unhandled Exception {0}." -f $_.Exception.Message) -Level $ErrorLvl
throw
}
}
function Assign-Roles {
<#
.SYNOPSIS
Assigns role Assignment for the scope specified.
.DESCRIPTION
This command will assign role Assignment for the scope specified.
.PARAMETER RoleDefinitionId
Role Definition Id.
.PARAMETER Scope
Role Definition Id.
.EXAMPLE
Assign-Roles -RoleDefinitionId RoleDefinitionId -Scope Scope
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[String]$RoleDefinitionId,
[Parameter(Mandatory = $true, Position = 1)]
[String]$Scope
)
try {
$payload = ConvertFrom-Json $RoleAssignmentPayload
$newRoleAssignmentGuid = (New-Guid).Guid.ToString()
$payload.Id = $newRoleAssignmentGuid
$payload.Properties.PrincipalId = $Global:UserManagedIdentityPrincipalId
$payload.Properties.RoleDefinitionId = ($AzureRoleDefinitionPath -f $RoleDefinitionId)
$payload.Properties.Scope = $Scope
$payload = ConvertTo-Json $payload -Depth $MaxDepth
$response = Invoke-ArmApi-WithPath -Path ($AzureRoleAssignmentPath -f $Scope, $newRoleAssignmentGuid) -ApiVersion $AzureRoleAssignmentApiVersion -Method $PUT -Payload $payload
if ($null -eq $response.Response.Id) {
Write-Telemetry -Message ("Failed to assign role {0} to scope {1}." -f , $RoleDefinitionId, $Scope)
}
else {
Write-Telemetry -Message ("Successfully assigned role {0} to scope {1}." -f , $RoleDefinitionId, $Scope)
}
}
catch [Exception] {
Write-Telemetry -Message ("Unhandled Exception {0}." -f $_.Exception.Message) -Level $ErrorLvl
throw
}
}
function Get-AllSoftwareUpdateConfigurations {
<#
.SYNOPSIS
Gets all software update configurations.
.DESCRIPTION
This function gets all software update configurations with support for pagination.
.PARAMETER AutomationAccountResourceId
Automation account resource id.
.EXAMPLE
Get-AllSoftwareUpdateConfigurations -AutomationAccountResourceId "/subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Automation/automationAccounts/{aaName}"
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[String]$AutomationAccountResourceId
)
$output = $null
$skip = 0
do {
$path = ($SoftwareUpdateConfigurationsPath -f $AutomationAccountResourceId, $skip)
$output = Invoke-ArmApi-WithPath -Path $path -ApiVersion $SoftwareUpdateConfigurationApiVersion -Method $GET
if ($output.Status -eq $Failed) {
Write-Telemetry -Message ("Failed to get software update configurations with error code {0} and error message {1}." -f $output.ErrorCode, $output.ErrorMessage)
throw
}
foreach ($result in $output.Response.value) {
if (!$Global:SoftwareUpdateConfigurationsResourceIDs.ContainsKey($result.id)) {
$Global:SoftwareUpdateConfigurationsResourceIDs[$result.id] = $result.name
}
}
# API paginates in multiples of 100.
$skip = $skip + 100
}
while ($null -ne $output.Response.nextLink);
}
function Add-RoleAssignmentsForAzureDynamicMachinesScope {
<#
.SYNOPSIS
Adds required roles assignments for Azure dynamic machines scope.
.DESCRIPTION
This command will add required roles assignments for Azure dynamic machines scope.
.PARAMETER AutomationAccountResourceId
Automation Account Resource Id.
.EXAMPLE
Add-RoleAssignmentsForAzureDynamicMachinesScope -AutomationAccountResourceId "/subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Automation/automationAccounts/{aaName}"
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, Position = 1)]
[String]$AutomationAccountResourceId
)
Get-AllSoftwareUpdateConfigurations -AutomationAccountResourceId $AutomationAccountResourceId
$softwareUpdateConfigurations = [System.Collections.ArrayList]@($Global:SoftwareUpdateConfigurationsResourceIDs.Keys)
foreach ($softwareUpdateConfiguration in $softwareUpdateConfigurations) {
try {
$softwareUpdateConfigurationData = Invoke-ArmApi-WithPath -Path $softwareUpdateConfiguration -ApiVersion $SoftwareUpdateConfigurationApiVersion -Method $GET
if ($softwareUpdateConfigurationData.Status -eq $Failed) {
Write-Telemetry -Message ("Failed to get software update configuration {0} with error code {1} and error message {2}." -f $softwareUpdateConfiguration, $softwareUpdateConfigurationData.ErrorCode, $softwareUpdateConfigurationData.ErrorMessage) -Level $ErrorLvl
}
elseif ($null -ne $softwareUpdateConfigurationData.Response.properties.updateConfiguration.targets.azureQueries) {
foreach ($azureQuery in $softwareUpdateConfigurationData.Response.properties.updateConfiguration.targets.azureQueries) {
foreach ($scope in $azureQuery.scope) {
try {
if (!$Global:AzureDynamicQueriesScope.ContainsKey($scope)) {
$scopeAtSubscriptionLevel = $scope.Split("/")
# Register subscription in query with Microsoft.Maintenance Resource Provider.
Register-MaintenanceResourceProviderToSubscription -ResourceId $scope
# Virtual machine contributor access for the scope to run arg queries and set patch properties and config assignments
Assign-Roles -RoleDefinitionId $VirtualMachineContributorRole -Scope $scope
# Scheduled patching contributor role for configuration assignments at the subscription level.
Assign-Roles -RoleDefinitionId $ScheduledPatchingContributorRole -Scope ("/subscriptions/" + $scopeAtSubscriptionLevel[2])
# Save in dictionary to avoid reassigning roles for the same scope again.
$Global:AzureDynamicQueriesScope[$scope] = $true
}
}
catch [Exception] {
Write-Telemetry -Message ("Unhandled Exception {0}." -f $_.Exception.Message) -Level $ErrorLvl
}
}
}
}
}
catch [Exception] {
Write-Telemetry -Message ("Unhandled Exception {0}." -f $_.Exception.Message) -Level $ErrorLvl
}
}
}
function Add-RoleAssignmentsForMachines {
<#
.SYNOPSIS
Adds required roles assignments for automation account.
.DESCRIPTION
This command will add required roles assignments for automation account.
.EXAMPLE
Add-RoleAssignmentsForMachines
#>
foreach ($machine in $Global:Machines) {
try {
# Register subscription to which machine belongs with Microsoft.Maintenance Resource Provider.
Register-MaintenanceResourceProviderToSubscription -ResourceId $machine
if ($machine -Match "microsoft.hybridcompute") {
# Arc machine contributor access for arc machines.