-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Expand file tree
/
Copy pathInitialize-AzMigrateLocalReplicationInfrastructure.ps1
More file actions
1230 lines (1079 loc) · 65.8 KB
/
Initialize-AzMigrateLocalReplicationInfrastructure.ps1
File metadata and controls
1230 lines (1079 loc) · 65.8 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
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------
<#
.Synopsis
Initializes the infrastructure for the migrate project.
.Description
The Initialize-AzMigrateLocalReplicationInfrastructure cmdlet initializes the infrastructure for the migrate project in AzLocal scenario.
.Link
https://learn.microsoft.com/powershell/module/az.migrate/initialize-azmigratelocalreplicationinfrastructure
#>
function Initialize-AzMigrateLocalReplicationInfrastructure {
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PreviewMessageAttribute("This cmdlet is based on a preview API version and may experience breaking changes in future releases.")]
[OutputType([System.Boolean], ParameterSetName = 'AzLocal')]
[CmdletBinding(DefaultParameterSetName = 'AzLocal', PositionalBinding = $false, SupportsShouldProcess, ConfirmImpact = 'Medium')]
param(
[Parameter(Mandatory)]
[ValidateNotNull()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the Resource Group of the Azure Migrate Project in the current subscription.
${ResourceGroupName},
[Parameter(Mandatory)]
[ValidateNotNull()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the name of the Azure Migrate project to be used for server migration.
${ProjectName},
[Parameter()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the Storage Account ARM Id to be used for private endpoint scenario.
${CacheStorageAccountId},
[Parameter()]
[System.String]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.DefaultInfo(Script = '(Get-AzContext).Subscription.Id')]
# Azure Subscription ID.
${SubscriptionId},
[Parameter(Mandatory)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the source appliance name for the AzLocal scenario.
${SourceApplianceName},
[Parameter(Mandatory)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the target appliance name for the AzLocal scenario.
${TargetApplianceName},
[Parameter()]
[Alias('AzureRMContext', 'AzureCredential')]
[ValidateNotNull()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Azure')]
[System.Management.Automation.PSObject]
# The credentials, account, tenant, and subscription used for communication with Azure.
${DefaultProfile},
[Parameter(DontShow)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Runtime')]
[System.Management.Automation.SwitchParameter]
# Wait for .NET debugger to attach
${Break},
[Parameter(DontShow)]
[ValidateNotNull()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Runtime')]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SendAsyncStep[]]
# SendAsync Pipeline Steps to be appended to the front of the pipeline
${HttpPipelineAppend},
[Parameter()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Runtime')]
[System.Management.Automation.SwitchParameter]
# Returns true when the command succeeds
${PassThru},
[Parameter(DontShow)]
[ValidateNotNull()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Runtime')]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SendAsyncStep[]]
# SendAsync Pipeline Steps to be prepended to the front of the pipeline
${HttpPipelinePrepend},
[Parameter(DontShow)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Runtime')]
[System.Uri]
# The URI for the proxy server to use
${Proxy},
[Parameter(DontShow)]
[ValidateNotNull()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Runtime')]
[System.Management.Automation.PSCredential]
# Credentials for a proxy server to use for the remote call
${ProxyCredential},
[Parameter(DontShow)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Runtime')]
[System.Management.Automation.SwitchParameter]
# Use the default credentials for the proxy
${ProxyUseDefaultCredentials}
)
process {
$helperPath = [System.IO.Path]::Combine($PSScriptRoot, "Helper", "AzLocalCommonSettings.ps1")
Import-Module $helperPath
$helperPath = [System.IO.Path]::Combine($PSScriptRoot, "Helper", "AzLocalCommonHelper.ps1")
Import-Module $helperPath
CheckResourcesModuleDependency
CheckStorageModuleDependency
Import-Module Az.Resources
Import-Module Az.Storage
$hasCacheStorageAccountId = $PSBoundParameters.ContainsKey('CacheStorageAccountId')
$parameterSetName = $PSCmdlet.ParameterSetName
$null = $PSBoundParameters.Remove('ResourceGroupName')
$null = $PSBoundParameters.Remove('ProjectName')
$null = $PSBoundParameters.Remove('CacheStorageAccountId')
$null = $PSBoundParameters.Remove('SourceApplianceName')
$null = $PSBoundParameters.Remove('TargetApplianceName')
# Set common ErrorVariable and ErrorAction for get behaviors
$null = $PSBoundParameters.Add('ErrorVariable', 'notPresent')
$null = $PSBoundParameters.Add('ErrorAction', 'SilentlyContinue')
# Get subscription Id
$context = Get-AzContext
if ([string]::IsNullOrEmpty($SubscriptionId)) {
Write-Host "No -SubscriptionId provided. Using the one from Get-AzContext."
$SubscriptionId = $context.Subscription.Id
if ([string]::IsNullOrEmpty($SubscriptionId)) {
throw "Please login to Azure to select a subscription."
}
}
Write-Host "*Selected Subscription Id: '$($SubscriptionId)'"
# Get resource group with Name
$resourceGroup = Get-AzResourceGroup `
-Name $ResourceGroupName `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
if ($null -eq $resourceGroup) {
throw "Resource group '$($ResourceGroupName)' does not exist in the subscription. Please create the resource group and try again."
}
Write-Host "*Selected Resource Group: '$($ResourceGroupName)'"
# Verify user validity
$userObject = Get-AzADUser -UserPrincipalName $context.Subscription.ExtendedProperties.Account
if (-not $userObject) {
$userObject = Get-AzADUser -Mail $context.Subscription.ExtendedProperties.Account
}
if (-not $userObject) {
$mailNickname = "{0}#EXT#" -f $($context.Account.Id -replace '@', '_')
$userObject = Get-AzADUser |
Where-Object { $_.MailNickname -eq $mailNickname }
}
if (-not $userObject) {
if ($context.Account.Id.StartsWith("MSI@")) {
$hostname = $env:COMPUTERNAME
$userObject = Get-AzADServicePrincipal -DisplayName $hostname
}
else {
$userObject = Get-AzADServicePrincipal -ApplicationID $context.Account.Id
}
}
if (-not $userObject) {
throw 'User Object Id Not Found!'
}
# Get Migrate Project with ResourceGroupName, Name
$null = $PSBoundParameters.Add('ResourceGroupName', $ResourceGroupName)
$null = $PSBoundParameters.Add('Name', $ProjectName)
$migrateProject = Get-AzMigrateProject @PSBoundParameters
if ($null -eq $migrateProject)
{
throw "Migrate project '$ProjectName' not found."
}
elseif ($migrateProject.Property.ProvisioningState -ne [ProvisioningState]::Succeeded)
{
throw "Migrate project '$ProjectName' is not in a valid state. The provisioning state is '$($migrateProject.Property.ProvisioningState)'. Please verify your Azure Migrate project setup."
}
$null = $PSBoundParameters.Remove('Name')
# Get Data Replication Service (AMH solution) with ResourceGroupName, MigrateProjectName, Name
$amhSolutionName = $AzMigrateSolutions.DataReplicationSolution
$null = $PSBoundParameters.Add('MigrateProjectName', $ProjectName)
$null = $PSBoundParameters.Add('Name', $amhSolutionName)
$amhSolution = Az.Migrate.private\Get-AzMigrateSolution_Get @PSBoundParameters
if ($null -eq $amhSolution)
{
throw New-AzMigrateSolutionNotFoundException `
-Name $amhSolutionName `
-ResourceGroupName $ResourceGroupName `
-ProjectName $ProjectName
}
$null = $PSBoundParameters.Remove('Name')
$null = $PSBoundParameters.Remove('MigrateProjectName')
# Validate Replication Vault
$replicationVaultName = $amhSolution.DetailExtendedDetail["vaultId"].Split("/")[8]
if ([string]::IsNullOrEmpty($replicationVaultName)) {
throw "No Replication Vault found. Please verify your Azure Migrate project setup."
}
# Get replication vault with ResourceGroupName, Name
$null = $PSBoundParameters.Add('Name', $replicationVaultName)
$replicationVault = Az.Migrate.Internal\Get-AzMigrateVault @PSBoundParameters
if ($null -eq $replicationVault)
{
throw "No Replication Vault '$replicationVaultName' found in Resource Group '$ResourceGroupName'. Please verify your Azure Migrate project setup."
}
$null = $PSBoundParameters.Remove('Name')
# Access Discovery Service
# Get Discovery Solution with ResourceGroupName, MigrateProjectName, Name
$discoverySolutionName = $AzMigrateSolutions.DiscoverySolution
$null = $PSBoundParameters.Add('MigrateProjectName', $ProjectName)
$null = $PSBoundParameters.Add('Name', $discoverySolutionName)
$discoverySolution = Az.Migrate.private\Get-AzMigrateSolution_Get @PSBoundParameters
if ($null -eq $discoverySolution)
{
throw throw New-AzMigrateSolutionNotFoundException `
-Name $discoverySolutionName `
-ResourceGroupName $ResourceGroupName `
-ProjectName $ProjectName
}
$null = $PSBoundParameters.Remove('Name')
$null = $PSBoundParameters.Remove('MigrateProjectName')
# Get Appliances Mapping
$appMap = @{}
if ($null -ne $discoverySolution.DetailExtendedDetail["applianceNameToSiteIdMapV2"]) {
$appMapV2 = $discoverySolution.DetailExtendedDetail["applianceNameToSiteIdMapV2"] | ConvertFrom-Json
# Fetch all appliance from V2 map first. Then these can be updated if found again in V3 map.
foreach ($item in $appMapV2) {
$appMap[$item.ApplianceName.ToLower()] = $item.SiteId
}
}
if ($null -ne $discoverySolution.DetailExtendedDetail["applianceNameToSiteIdMapV3"]) {
$appMapV3 = $discoverySolution.DetailExtendedDetail["applianceNameToSiteIdMapV3"] | ConvertFrom-Json
foreach ($item in $appMapV3) {
$t = $item.psobject.properties
$appMap[$t.Name.ToLower()] = $t.Value.SiteId
}
}
if ($null -eq $discoverySolution.DetailExtendedDetail["applianceNameToSiteIdMapV2"] -And
$null -eq $discoverySolution.DetailExtendedDetail["applianceNameToSiteIdMapV3"] ) {
throw "Server Discovery Solution missing Appliance Details. Invalid Solution."
}
$hyperVSiteTypeRegex = "(?<=/Microsoft.OffAzure/HyperVSites/).*$"
$vmwareSiteTypeRegex = "(?<=/Microsoft.OffAzure/VMwareSites/).*$"
# Validate SourceApplianceName & TargetApplianceName
$sourceSiteId = $appMap[$SourceApplianceName.ToLower()]
$targetSiteId = $appMap[$TargetApplianceName.ToLower()]
if ($sourceSiteId -match $hyperVSiteTypeRegex -and $targetSiteId -match $hyperVSiteTypeRegex) {
$instanceType = $AzLocalInstanceTypes.HyperVToAzLocal
$fabricInstanceType = $FabricInstanceTypes.HyperVInstance
}
elseif ($sourceSiteId -match $vmwareSiteTypeRegex -and $targetSiteId -match $hyperVSiteTypeRegex) {
$instanceType = $AzLocalInstanceTypes.VMwareToAzLocal
$fabricInstanceType = $FabricInstanceTypes.VmwareInstance
}
else {
throw "Error encountered in matching the given source appliance name '$SourceApplianceName' and target appliance name '$TargetApplianceName'. Please verify the VM site type to be either for HyperV or VMware for both source and target appliances, and the appliance names are correct."
}
# Get healthy asrv2 fabrics with ResourceGroupName
$allFabrics = Az.Migrate.private\Get-AzMigrateLocalReplicationFabric_List1 @PSBoundParameters `
| Where-Object {
$_.Property.ProvisioningState -eq [ProvisioningState]::Succeeded -and
$_.Property.CustomProperty.MigrationSolutionId -eq $amhSolution.Id
}
# Filter for source fabric
$sourceFabric = $allFabrics | Where-Object {
$_.Property.CustomProperty.InstanceType -ceq $fabricInstanceType -and
$_.Name.StartsWith($SourceApplianceName, [System.StringComparison]::InvariantCultureIgnoreCase)
}
if ($null -eq $sourceFabric)
{
throw "Couldn't find connected source appliance with the name '$SourceApplianceName'. Deploy a source appliance by completing the Discover step of migration for your on-premises environment."
}
Write-Host "*Selected Source Fabric: '$($sourceFabric.Name)'"
# Get source fabric agent (dra) with ResourceGroupName, FabricName
$null = $PSBoundParameters.Add('FabricName', $sourceFabric.Name)
$sourceDras = Az.Migrate.Internal\Get-AzMigrateFabricAgent @PSBoundParameters
$sourceDra = $sourceDras | Where-Object {
$_.Property.MachineName -eq $SourceApplianceName -and
$_.Property.CustomProperty.InstanceType -eq $fabricInstanceType -and
$_.Property.IsResponsive -eq $true
}
if ($null -eq $sourceDra)
{
throw "The source appliance '$SourceApplianceName' is in a disconnected state. Ensure that the source appliance is running and has connectivity before proceeding."
}
$null = $PSBoundParameters.Remove('FabricName')
$sourceDra = $sourceDra[0]
Write-Host "*Selected Source Fabric Agent: '$($sourceDra.Name)'"
# Filter for target fabric
$fabricInstanceType = $FabricInstanceTypes.AzLocalInstance
$targetFabric = $allFabrics | Where-Object {
$_.Property.CustomProperty.InstanceType -ceq $fabricInstanceType -and
$_.Name.StartsWith($TargetApplianceName, [System.StringComparison]::InvariantCultureIgnoreCase)
}
if ($null -eq $targetFabric)
{
throw "Couldn't find connected target appliance with the name '$TargetApplianceName'. Deploy a target appliance by completing the Configuration step of migration for your Azure Local environment."
}
"*Selected Target Fabric: '$($targetFabric.Name)'"
# Get target fabric agent (dra) with ResourceGroupName, FabricName
$null = $PSBoundParameters.Add('FabricName', $targetFabric.Name)
$targetDras = Az.Migrate.Internal\Get-AzMigrateFabricAgent @PSBoundParameters
$targetDra = $targetDras | Where-Object {
$_.Property.MachineName -eq $TargetApplianceName -and
$_.Property.CustomProperty.InstanceType -eq $fabricInstanceType -and
$_.Property.IsResponsive -eq $true
}
if ($null -eq $targetDra)
{
throw "The target appliance '$TargetApplianceName' is in a disconnected state. Ensure that the target appliance is running and has connectivity before proceeding."
}
$null = $PSBoundParameters.Remove('FabricName')
$targetDra = $targetDras[0]
Write-Host "*Selected Target Fabric Agent: '$($targetDra.Name)'"
# Put Policy
# Get replication policy with ResourceGroupName, Name, VaultName
$policyName = $replicationVault.Name + $instanceType + "policy"
$null = $PSBoundParameters.Add('Name', $policyName)
$null = $PSBoundParameters.Add('VaultName', $replicationVault.Name)
$policy = Az.Migrate.Internal\Get-AzMigratePolicy @PSBoundParameters
# Default policy is found
if ($null -ne $policy) {
# Give time for create/update to reach a terminal state. Timeout after 10min
if ($policy.Property.ProvisioningState -eq [ProvisioningState]::Creating -or
$policy.Property.ProvisioningState -eq [ProvisioningState]::Updating) {
Write-Host "Policy '$($policyName)' found in Provisioning State '$($policy.Property.ProvisioningState)'."
for ($i = 0; $i -lt 20; $i++) {
Start-Sleep -Seconds 30
$policy = Az.Migrate.Internal\Get-AzMigratePolicy -InputObject $policy
if (-not (
$policy.Property.ProvisioningState -eq [ProvisioningState]::Creating -or
$policy.Property.ProvisioningState -eq [ProvisioningState]::Updating)) {
break
}
}
# Make sure Policy is no longer in Creating or Updating state
if ($policy.Property.ProvisioningState -eq [ProvisioningState]::Creating -or
$policy.Property.ProvisioningState -eq [ProvisioningState]::Updating) {
throw "Policy '$($policyName)' times out with Provisioning State: '$($policy.Property.ProvisioningState)'. Please re-run this command or contact support if help needed."
}
}
# Check and remove if policy is in a bad terminal state
if ($policy.Property.ProvisioningState -eq [ProvisioningState]::Canceled -or
$policy.Property.ProvisioningState -eq [ProvisioningState]::Failed) {
Write-Host "Policy '$($policyName)' found but in an unusable terminal Provisioning State '$($policy.Property.ProvisioningState)'.`nRemoving policy..."
# Remove policy
try {
Az.Migrate.Internal\Remove-AzMigratePolicy -InputObject $policy | Out-Null
}
catch {
if ($_.Exception.Message -notmatch "Status: OK") {
throw $_.Exception.Message
}
}
Start-Sleep -Seconds 30
$policy = Az.Migrate.Internal\Get-AzMigratePolicy `
-InputObject $policy `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
# Make sure Policy is no longer in Canceled or Failed state
if ($null -ne $policy -and
($policy.Property.ProvisioningState -eq [ProvisioningState]::Canceled -or
$policy.Property.ProvisioningState -eq [ProvisioningState]::Failed)) {
throw "Failed to change the Provisioning State of policy '$($policyName)'by removing. Please re-run this command or contact support if help needed."
}
}
# Give time to remove policy. Timeout after 10min
if ($null -eq $policy -and $policy.Property.ProvisioningState -eq [ProvisioningState]::Deleting) {
Write-Host "Policy '$($policyName)' found in Provisioning State '$($policy.Property.ProvisioningState)'."
for ($i = 0; $i -lt 20; $i++) {
Start-Sleep -Seconds 30
$policy = Az.Migrate.Internal\Get-AzMigratePolicy `
-InputObject $policy `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
if ($null -eq $policy -or $policy.Property.ProvisioningState -eq [ProvisioningState]::Deleted) {
break
}
elseif ($policy.Property.ProvisioningState -eq [ProvisioningState]::Deleting) {
continue
}
throw "Policy '$($policyName)' has an unexpected Provisioning State of '$($policy.Property.ProvisioningState)' during removal process. Please re-run this command or contact support if help needed."
}
# Make sure Policy is no longer in Deleting state
if ($null -ne $policy -and $policy.Property.ProvisioningState -eq [ProvisioningState]::Deleting) {
throw "Policy '$($policyName)' times out with Provisioning State: '$($policy.Property.ProvisioningState)'. Please re-run this command or contact support if help needed."
}
}
# Indicate policy was removed
if ($null -eq $policy -or $policy.Property.ProvisioningState -eq [ProvisioningState]::Deleted) {
Write-Host "Policy '$($policyName)' was removed."
}
}
# Refresh local policy object if exists
if ($null -ne $policy) {
$policy = Az.Migrate.Internal\Get-AzMigratePolicy -InputObject $policy
}
# Create policy if not found or previously deleted
if ($null -eq $policy -or $policy.Property.ProvisioningState -eq [ProvisioningState]::Deleted) {
Write-Host "Creating Policy..."
$params = @{
InstanceType = $instanceType;
RecoveryPointHistoryInMinute = $ReplicationDetails.PolicyDetails.DefaultRecoveryPointHistoryInMinutes;
CrashConsistentFrequencyInMinute = $ReplicationDetails.PolicyDetails.DefaultCrashConsistentFrequencyInMinutes;
AppConsistentFrequencyInMinute = $ReplicationDetails.PolicyDetails.DefaultAppConsistentFrequencyInMinutes;
}
# Setup Policy deployment parameters
$policyProperties = [Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.PolicyModelProperties]::new()
if ($instanceType -eq $AzLocalInstanceTypes.HyperVToAzLocal) {
$policyCustomProperties = [Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.HyperVToAzStackHcipolicyModelCustomProperties]::new()
}
elseif ($instanceType -eq $AzLocalInstanceTypes.VMwareToAzLocal) {
$policyCustomProperties = [Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.VMwareToAzStackHcipolicyModelCustomProperties]::new()
}
else {
throw "Instance type '$($instanceType)' is not supported. Currently, for AzLocal scenario, only HyperV and VMware as the source is supported."
}
$policyCustomProperties.InstanceType = $params.InstanceType
$policyCustomProperties.RecoveryPointHistoryInMinute = $params.RecoveryPointHistoryInMinute
$policyCustomProperties.CrashConsistentFrequencyInMinute = $params.CrashConsistentFrequencyInMinute
$policyCustomProperties.AppConsistentFrequencyInMinute = $params.AppConsistentFrequencyInMinute
$policyProperties.CustomProperty = $policyCustomProperties
try {
Az.Migrate.Internal\New-AzMigratePolicy `
-Name $policyName `
-ResourceGroupName $ResourceGroupName `
-VaultName $replicationVaultName `
-Property $policyProperties `
-SubscriptionId $SubscriptionId `
-NoWait | Out-Null
}
catch {
if ($_.Exception.Message -notmatch "Status: OK") {
throw $_.Exception.Message
}
}
# Check Policy creation status every 30s. Timeout after 10min
for ($i = 0; $i -lt 20; $i++) {
Start-Sleep -Seconds 30
$policy = Az.Migrate.Internal\Get-AzMigratePolicy @PSBoundParameters
if ($null -eq $policy)
{
continue
}
# Stop if policy reaches a terminal state
if ($policy.Property.ProvisioningState -eq [ProvisioningState]::Succeeded -or
$policy.Property.ProvisioningState -eq [ProvisioningState]::Deleted -or
$policy.Property.ProvisioningState -eq [ProvisioningState]::Canceled -or
$policy.Property.ProvisioningState -eq [ProvisioningState]::Failed) {
break
}
}
# Make sure Policy is in a terminal state
if (-not (
$policy.Property.ProvisioningState -eq [ProvisioningState]::Succeeded -or
$policy.Property.ProvisioningState -eq [ProvisioningState]::Deleted -or
$policy.Property.ProvisioningState -eq [ProvisioningState]::Canceled -or
$policy.Property.ProvisioningState -eq [ProvisioningState]::Failed)) {
throw "Policy '$($policyName)' times out with Provisioning State: '$($policy.Property.ProvisioningState)' during creation process. Please re-run this command or contact support if help needed."
}
}
if ($policy.Property.ProvisioningState -ne [ProvisioningState]::Succeeded) {
throw "Policy '$($policyName)' has an unexpected Provisioning State of '$($policy.Property.ProvisioningState)'. Please re-run this command or contact support if help needed."
}
$policy = Az.Migrate.Internal\Get-AzMigratePolicy @PSBoundParameters
if ($null -eq $policy)
{
throw "Unexpected error occurred during policy creation. Please re-run this command or contact support if help needed."
}
elseif ($policy.Property.ProvisioningState -ne [ProvisioningState]::Succeeded)
{
throw "Policy '$($policyName)' has an unexpected Provisioning State of '$($policy.Property.ProvisioningState)'. Please re-run this command or contact support if help needed."
}
else
{
Write-Host "*Selected Policy: '$($policyName)'"
}
$null = $PSBoundParameters.Remove('Name')
$null = $PSBoundParameters.Remove('VaultName')
# Put Cache Storage Account
# Get AMH solution with ResourceGroupName, MigrateProjectName, Name
$null = $PSBoundParameters.Add('MigrateProjectName', $ProjectName)
$null = $PSBoundParameters.Add('Name', $amhSolutionName)
$amhSolution = Az.Migrate.private\Get-AzMigrateSolution_Get @PSBoundParameters
if ($null -eq $amhSolution)
{
throw New-AzMigrateSolutionNotFoundException `
-Name $amhSolutionName `
-ResourceGroupName $ResourceGroupName `
-ProjectName $ProjectName
}
$null = $PSBoundParameters.Remove('Name')
$null = $PSBoundParameters.Remove('MigrateProjectName')
$amhStoredStorageAccountId = $amhSolution.DetailExtendedDetail["replicationStorageAccountId"]
# Record of rsa found in AMH solution
if (![string]::IsNullOrEmpty($amhStoredStorageAccountId)) {
# Get amhStoredStorageAccount with ResourceGroupName, Name
$amhStoredStorageAccountName = $amhStoredStorageAccountId.Split("/")[8]
$amhStoredStorageAccount = Get-AzStorageAccount `
-ResourceGroupName $ResourceGroupName `
-Name $amhStoredStorageAccountName `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
# Wait for amhStoredStorageAccount to reach a terminal state
if ($null -ne $amhStoredStorageAccount -and
$null -ne $amhStoredStorageAccount.ProvisioningState -and
$amhStoredStorageAccount.ProvisioningState -ne [StorageAccountProvisioningState]::Succeeded) {
# Check rsa state every 30s if not Succeeded already. Timeout after 10min
for ($i = 0; $i -lt 20; $i++) {
Start-Sleep -Seconds 30
$amhStoredStorageAccount = Get-AzStorageAccount `
-ResourceGroupName $ResourceGroupName `
-Name $amhStoredStorageAccountName `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
# Stop if amhStoredStorageAccount is not found or in a terminal state
if ($null -eq $amhStoredStorageAccount -or
$null -eq $amhStoredStorageAccount.ProvisioningState -or
$amhStoredStorageAccount.ProvisioningState -eq [StorageAccountProvisioningState]::Succeeded) {
break
}
}
}
# amhStoredStorageAccount exists and in Succeeded state
if ($null -ne $amhStoredStorageAccount -and
$amhStoredStorageAccount.ProvisioningState -eq [StorageAccountProvisioningState]::Succeeded)
{
# Use amhStoredStorageAccount and ignore user provided Cache Storage Account Id
if (![string]::IsNullOrEmpty($CacheStorageAccountId) -and $amhStoredStorageAccount.Id -ne $CacheStorageAccountId)
{
Write-Host "A Cache Storage Account '$($amhStoredStorageAccountName)' has been linked already. The given -CacheStorageAccountId '$($CacheStorageAccountId)' will be ignored."
}
$cacheStorageAccount = $amhStoredStorageAccount
# This will fix brownfield issue where AMH solution tool is set incorrectly that causes UX bifurcation to go to the wrong experience;
# for new projects that are set correctly from the start, this will essentially be a no-op.
Az.Migrate.Internal\Set-AzMigrateSolution `
-MigrateProjectName $ProjectName `
-Name $amhSolution.Name `
-ResourceGroupName $ResourceGroupName `
-DetailExtendedDetail $amhSolution.DetailExtendedDetail.AdditionalProperties `
-Tool $DataReplicationSolutionSettings.Tool `
-Purpose $DataReplicationSolutionSettings.Purpose | Out-Null
}
elseif ($null -eq $amhStoredStorageAccount -or $null -eq $amhStoredStorageAccount.ProvisioningState)
{
# amhStoredStorageAccount is found but in a bad state, so log to ask user to remove
if ($null -ne $amhStoredStorageAccount -and $null -eq $amhStoredStorageAccount.ProvisioningState)
{
Write-Host "A previously linked Cache Storage Account with Id '$($amhStoredStorageAccountId)' is found but in a unusable state. Please remove it manually and re-run this command."
}
# amhStoredStorageAccount is not found or in a bad state but AMH has a record of it, so remove the record
if ($amhSolution.DetailExtendedDetail.ContainsKey("replicationStorageAccountId"))
{
$amhSolution.DetailExtendedDetail.Remove("replicationStorageAccountId") | Out-Null
$amhSolution.DetailExtendedDetail.Add("replicationStorageAccountId", $null) | Out-Null
Az.Migrate.Internal\Set-AzMigrateSolution `
-MigrateProjectName $ProjectName `
-Name $amhSolution.Name `
-ResourceGroupName $ResourceGroupName `
-DetailExtendedDetail $amhSolution.DetailExtendedDetail.AdditionalProperties `
-Tool $DataReplicationSolutionSettings.Tool `
-Purpose $DataReplicationSolutionSettings.Purpose | Out-Null
}
}
else
{
throw "A linked Cache Storage Account with Id '$($amhStoredStorageAccountId)' times out with Provisioning State: '$($amhStoredStorageAccount.ProvisioningState)'. Please re-run this command or contact support if help needed."
}
# Refresh AMH solution with ResourceGroupName, MigrateProjectName, Name
$null = $PSBoundParameters.Add('MigrateProjectName', $ProjectName)
$null = $PSBoundParameters.Add('Name', $amhSolutionName)
$amhSolution = Az.Migrate.private\Get-AzMigrateSolution_Get @PSBoundParameters
if ($null -eq $amhSolution)
{
throw New-AzMigrateSolutionNotFoundException `
-Name $amhSolutionName `
-ResourceGroupName $ResourceGroupName `
-ProjectName $ProjectName
}
# Check if AMH record is removed
if (($null -eq $amhStoredStorageAccount -or $null -eq $amhStoredStorageAccount.ProvisioningState) -and
![string]::IsNullOrEmpty($amhSolution.DetailExtendedDetail["replicationStorageAccountId"])) {
throw "Unexpected error occurred in unlinking Cache Storage Account with Id '$($amhSolution.DetailExtendedDetail["replicationStorageAccountId"])'. Please re-run this command or contact support if help needed."
}
$null = $PSBoundParameters.Remove('Name')
$null = $PSBoundParameters.Remove('MigrateProjectName')
}
# No linked Cache Storage Account found in AMH solution but user provides a Cache Storage Account Id
if ($null -eq $cacheStorageAccount -and ![string]::IsNullOrEmpty($CacheStorageAccountId)) {
$userProvidedStorageAccountIdSegs = $CacheStorageAccountId.Split("/")
if ($userProvidedStorageAccountIdSegs.Count -ne 9) {
throw "Invalid Cache Storage Account Id '$($CacheStorageAccountId)' provided. Please provide a valid one."
}
$userProvidedStorageAccountName = ($userProvidedStorageAccountIdSegs[8]).ToLower()
# Check if user provided Cache Storage Account exists
# Get userProvidedStorageAccount with ResourceGroupName, Name
$userProvidedStorageAccount = Get-AzStorageAccount `
-ResourceGroupName $ResourceGroupName `
-Name $userProvidedStorageAccountName `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
# Wait for userProvidedStorageAccount to reach a terminal state
if ($null -ne $userProvidedStorageAccount -and
$null -ne $userProvidedStorageAccount.ProvisioningState -and
$userProvidedStorageAccount.ProvisioningState -ne [StorageAccountProvisioningState]::Succeeded) {
# Check rsa state every 30s if not Succeeded already. Timeout after 10min
for ($i = 0; $i -lt 20; $i++) {
Start-Sleep -Seconds 30
$userProvidedStorageAccount = Get-AzStorageAccount `
-ResourceGroupName $ResourceGroupName `
-Name $userProvidedStorageAccountName `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
# Stop if userProvidedStorageAccount is not found or in a terminal state
if ($null -eq $userProvidedStorageAccount -or
$null -eq $userProvidedStorageAccount.ProvisioningState -or
$userProvidedStorageAccount.ProvisioningState -eq [StorageAccountProvisioningState]::Succeeded) {
break
}
}
}
if ($null -ne $userProvidedStorageAccount -and
$userProvidedStorageAccount.ProvisioningState -eq [StorageAccountProvisioningState]::Succeeded) {
$cacheStorageAccount = $userProvidedStorageAccount
}
elseif ($null -eq $userProvidedStorageAccount) {
throw "Cache Storage Account with Id '$($CacheStorageAccountId)' is not found. Please re-run this command without -CacheStorageAccountId to create one automatically or re-create the Cache Storage Account yourself and try again."
}
elseif ($null -eq $userProvidedStorageAccount.ProvisioningState) {
throw "Cache Storage Account with Id '$($CacheStorageAccountId)' is found but in an unusable state. Please re-run this command without -CacheStorageAccountId to create one automatically or re-create the Cache Storage Account yourself and try again."
}
else {
throw "Cache Storage Account with Id '$($CacheStorageAccountId)' is found but times out with Provisioning State: '$($userProvidedStorageAccount.ProvisioningState)'. Please re-run this command or contact support if help needed."
}
}
# No Cache Storage Account found or provided, so create one
if ($null -eq $cacheStorageAccount) {
$suffix = (GenerateHashForArtifact -Artifact "$($sourceSiteId)/$($SourceApplianceName)").ToString()
if ($suffixHash.Length -gt 14) {
$suffix = $suffixHash.Substring(0, 14)
}
$cacheStorageAccountName = "migratersa" + $suffix
$cacheStorageAccountId = "/subscriptions/$($SubscriptionId)/resourceGroups/$($ResourceGroupName)/providers/Microsoft.Storage/storageAccounts/$($cacheStorageAccountName)"
# Check if default Cache Storage Account already exists, which it shouldn't
# Get cacheStorageAccount with ResourceGroupName, Name
$cacheStorageAccount = Get-AzStorageAccount `
-ResourceGroupName $ResourceGroupName `
-Name $cacheStorageAccountName `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
if ($null -ne $cacheStorageAccount) {
throw "Unexpected error encountered: Cache Storage Account '$($cacheStorageAccountName)' already exists. Please re-run this command to create a different one or contact support if help needed."
}
Write-Host "Creating Cache Storage Account with default name '$($cacheStorageAccountName)'..."
$params = @{
name = $cacheStorageAccountName;
location = $migrateProject.Location;
migrateProjectName = $migrateProject.Name;
skuName = "Standard_LRS";
tags = @{ "Migrate Project" = $migrateProject.Name };
kind = "StorageV2";
encryption = @{ services = @{blob = @{ enabled = $true }; file = @{ enabled = $true } } };
}
# Create Cache Storage Account
$cacheStorageAccount = New-AzStorageAccount `
-ResourceGroupName $ResourceGroupName `
-Name $params.name `
-SkuName $params.skuName `
-Location $params.location `
-Kind $params.kind `
-Tags $params.tags `
-AllowBlobPublicAccess $true
if ($null -ne $cacheStorageAccount -and
$null -ne $cacheStorageAccount.ProvisioningState -and
$cacheStorageAccount.ProvisioningState -ne [StorageAccountProvisioningState]::Succeeded) {
# Check rsa state every 30s if not Succeeded already. Timeout after 10min
# Get cacheStorageAccount with ResourceGroupName, Name
for ($i = 0; $i -lt 20; $i++) {
Start-Sleep -Seconds 30
$cacheStorageAccount = Get-AzStorageAccount `
-ResourceGroupName $ResourceGroupName `
-Name $cacheStorageAccountName `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
# Stop if cacheStorageAccount is not found or in a terminal state
if ($null -eq $cacheStorageAccount -or
$null -eq $cacheStorageAccount.ProvisioningState -or
$cacheStorageAccount.ProvisioningState -eq [StorageAccountProvisioningState]::Succeeded) {
break
}
}
}
if ($null -eq $cacheStorageAccount -or $null -eq $cacheStorageAccount.ProvisioningState) {
throw "Unexpected error occurs during Cache Storage Account creation process. Please re-run this command or provide -CacheStorageAccountId of the one created own your own."
}
elseif ($cacheStorageAccount.ProvisioningState -ne [StorageAccountProvisioningState]::Succeeded) {
throw "Cache Storage Account with Id '$($cacheStorageAccount.Id)' times out with Provisioning State: '$($cacheStorageAccount.ProvisioningState)' during creation process. Please remove it manually and re-run this command or contact support if help needed."
}
}
# Sanity check
if ($null -eq $cacheStorageAccount -or
$null -eq $cacheStorageAccount.ProvisioningState -or
$cacheStorageAccount.ProvisioningState -ne [StorageAccountProvisioningState]::Succeeded) {
throw "Unexpected error occurs during Cache Storage Account selection process. Please re-run this command or contact support if help needed."
}
$params = @{
contributorRoleDefId = [System.Guid]::parse($RoleDefinitionIds.ContributorId);
storageBlobDataContributorRoleDefId = [System.Guid]::parse($RoleDefinitionIds.StorageBlobDataContributorId);
sourceAppAadId = $sourceDra.Property.ResourceAccessIdentity.ObjectId;
targetAppAadId = $targetDra.Property.ResourceAccessIdentity.ObjectId;
}
# Grant vault Identity Aad access to Cache Storage Account
if (![string]::IsNullOrEmpty($replicationVault.IdentityPrincipalId))
{
$params.vaultIdentityAadId = $replicationVault.IdentityPrincipalId
# Grant vault Identity Aad access to Cache Storage Account as "Contributor"
$hasAadAppAccess = Get-AzRoleAssignment `
-ObjectId $params.vaultIdentityAadId `
-RoleDefinitionId $params.contributorRoleDefId `
-Scope $cacheStorageAccount.Id `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
if ($null -eq $hasAadAppAccess) {
New-AzRoleAssignment `
-ObjectId $params.vaultIdentityAadId `
-RoleDefinitionId $params.contributorRoleDefId `
-Scope $cacheStorageAccount.Id | Out-Null
}
# Grant vault Identity Aad access to Cache Storage Account as "StorageBlobDataContributor"
$hasAadAppAccess = Get-AzRoleAssignment `
-ObjectId $params.vaultIdentityAadId `
-RoleDefinitionId $params.storageBlobDataContributorRoleDefId `
-Scope $cacheStorageAccount.Id `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
if ($null -eq $hasAadAppAccess) {
New-AzRoleAssignment `
-ObjectId $params.vaultIdentityAadId `
-RoleDefinitionId $params.storageBlobDataContributorRoleDefId `
-Scope $cacheStorageAccount.Id | Out-Null
}
}
# Grant Source Dra AAD App access to Cache Storage Account as "Contributor"
$hasAadAppAccess = Get-AzRoleAssignment `
-ObjectId $params.sourceAppAadId `
-RoleDefinitionId $params.contributorRoleDefId `
-Scope $cacheStorageAccount.Id `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
if ($null -eq $hasAadAppAccess) {
New-AzRoleAssignment `
-ObjectId $params.sourceAppAadId `
-RoleDefinitionId $params.contributorRoleDefId `
-Scope $cacheStorageAccount.Id | Out-Null
}
# Grant Source Dra AAD App access to Cache Storage Account as "StorageBlobDataContributor"
$hasAadAppAccess = Get-AzRoleAssignment `
-ObjectId $params.sourceAppAadId `
-RoleDefinitionId $params.storageBlobDataContributorRoleDefId `
-Scope $cacheStorageAccount.Id `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
if ($null -eq $hasAadAppAccess) {
New-AzRoleAssignment `
-ObjectId $params.sourceAppAadId `
-RoleDefinitionId $params.storageBlobDataContributorRoleDefId `
-Scope $cacheStorageAccount.Id | Out-Null
}
# Grant Target Dra AAD App access to Cache Storage Account as "Contributor"
$hasAadAppAccess = Get-AzRoleAssignment `
-ObjectId $params.targetAppAadId `
-RoleDefinitionId $params.contributorRoleDefId `
-Scope $cacheStorageAccount.Id `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
if ($null -eq $hasAadAppAccess) {
New-AzRoleAssignment `
-ObjectId $params.targetAppAadId `
-RoleDefinitionId $params.contributorRoleDefId `
-Scope $cacheStorageAccount.Id | Out-Null
}
# Grant Target Dra AAD App access to Cache Storage Account as "StorageBlobDataContributor"
$hasAadAppAccess = Get-AzRoleAssignment `
-ObjectId $params.targetAppAadId `
-RoleDefinitionId $params.storageBlobDataContributorRoleDefId `
-Scope $cacheStorageAccount.Id `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
if ($null -eq $hasAadAppAccess) {
New-AzRoleAssignment `
-ObjectId $params.targetAppAadId `
-RoleDefinitionId $params.storageBlobDataContributorRoleDefId `
-Scope $cacheStorageAccount.Id | Out-Null
}
# Give time for role assignments to be created. Times out after 2min
$rsaPermissionGranted = $false
for ($i = 0; $i -lt 3; $i++) {
# Check Source Dra AAD App access to Cache Storage Account as "Contributor"
$hasAadAppAccess = Get-AzRoleAssignment `
-ObjectId $params.sourceAppAadId `
-RoleDefinitionId $params.contributorRoleDefId `
-Scope $cacheStorageAccount.Id `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
$rsaPermissionGranted = $null -ne $hasAadAppAccess
# Check Source Dra AAD App access to Cache Storage Account as "StorageBlobDataContributor"
$hasAadAppAccess = Get-AzRoleAssignment `
-ObjectId $params.sourceAppAadId `
-RoleDefinitionId $params.storageBlobDataContributorRoleDefId `
-Scope $cacheStorageAccount.Id `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
$rsaPermissionGranted = $rsaPermissionGranted -and ($null -ne $hasAadAppAccess)
# Check Target Dra AAD App access to Cache Storage Account as "Contributor"
$hasAadAppAccess = Get-AzRoleAssignment `
-ObjectId $params.targetAppAadId `
-RoleDefinitionId $params.contributorRoleDefId `
-Scope $cacheStorageAccount.Id `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
$rsaPermissionGranted = $rsaPermissionGranted -and ($null -ne $hasAadAppAccess)
# Check Target Dra AAD App access to Cache Storage Account as "StorageBlobDataContributor"
$hasAadAppAccess = Get-AzRoleAssignment `
-ObjectId $params.targetAppAadId `
-RoleDefinitionId $params.storageBlobDataContributorRoleDefId `
-Scope $cacheStorageAccount.Id `
-ErrorVariable notPresent `
-ErrorAction SilentlyContinue
$rsaPermissionGranted = $rsaPermissionGranted -and ($null -ne $hasAadAppAccess)
if ($rsaPermissionGranted) {
break
}
Start-Sleep -Seconds 30
}
if (!$rsaPermissionGranted) {
throw "Failed to grant Cache Storage Account permissions. Please re-run this command or contact support if help needed."
}
# Refresh AMH solution with ResourceGroupName, MigrateProjectName, Name
$null = $PSBoundParameters.Add('MigrateProjectName', $ProjectName)
$null = $PSBoundParameters.Add('Name', $amhSolutionName)
$amhSolution = Az.Migrate.private\Get-AzMigrateSolution_Get @PSBoundParameters
if ($null -eq $amhSolution)
{
throw New-AzMigrateSolutionNotFoundException `
-Name $amhSolutionName `
-ResourceGroupName $ResourceGroupName `
-ProjectName $ProjectName
}
$null = $PSBoundParameters.Remove('Name')
$null = $PSBoundParameters.Remove('MigrateProjectName')
if ($amhSolution.DetailExtendedDetail.ContainsKey("replicationStorageAccountId")) {
$amhStoredStorageAccountId = $amhSolution.DetailExtendedDetail["replicationStorageAccountId"]
if ([string]::IsNullOrEmpty($amhStoredStorageAccountId)) {
# Remove "replicationStorageAccountId" key
$amhSolution.DetailExtendedDetail.Remove("replicationStorageAccountId") | Out-Null
}
elseif ($amhStoredStorageAccountId -ne $cacheStorageAccount.Id) {
# Record of rsa mismatch
throw "Unexpected error occurred in linking Cache Storage Account with Id '$($cacheStorageAccount.Id)'. Please re-run this command or contact support if help needed."
}
}
# Update AMH record with chosen Cache Storage Account
if (!$amhSolution.DetailExtendedDetail.ContainsKey("replicationStorageAccountId"))
{
$amhSolution.DetailExtendedDetail.Add("replicationStorageAccountId", $cacheStorageAccount.Id)
Az.Migrate.Internal\Set-AzMigrateSolution `
-MigrateProjectName $ProjectName `
-Name $amhSolution.Name `
-ResourceGroupName $ResourceGroupName `
-DetailExtendedDetail $amhSolution.DetailExtendedDetail.AdditionalProperties `
-Tool $DataReplicationSolutionSettings.Tool `
-Purpose $DataReplicationSolutionSettings.Purpose | Out-Null
}
Write-Host "*Selected Cache Storage Account: '$($cacheStorageAccount.StorageAccountName)' in Resource Group '$($ResourceGroupName)' at Location '$($cacheStorageAccount.Location)' for Migrate Project '$($migrateProject.Name)'"
# Put replication extension
$replicationExtensionName = ($sourceFabric.Id -split '/')[-1] + "-" + ($targetFabric.Id -split '/')[-1] + "-MigReplicationExtn"
# Get replicationExtension with ResourceGroupName, VaultName, Name
$null = $PSBoundParameters.Add('Name', $replicationExtensionName)
$null = $PSBoundParameters.Add('VaultName', $replicationVaultName)
$replicationExtension = Az.Migrate.Internal\Get-AzMigrateReplicationExtension @PSBoundParameters
$null = $PSBoundParameters.Remove('Name')
$null = $PSBoundParameters.Remove('VaultName')
# Remove replication extension if does not match the selected Cache Storage Account