forked from JeffBow/AzurePowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClone-AzureRMresourceGroup.ps1
1610 lines (1284 loc) · 62.9 KB
/
Clone-AzureRMresourceGroup.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
Clones Azure V2 (ARM) resources from one resource group into a new resource group in the same Azure Subscriptions
Requires AzureRM module version 4.2.1 or later.
.DESCRIPTION
Copies configurations of a resource group into a new one
This is intended mostly for Azure V2 virtual machines and will include copying virtual disks, virtual
network, load balancers, Public IPs and other associated storage accounts, blob files and now managed disks.
Due to uniqueness requirements DNS names of source and targets, the following renaming occurs during reprovisioning
** Storage accounts will be renamed by appending an 8 character GUID to the original storage account name
** DNS Labels on Public IPs will be renamed by appending 'new' to the DNS name
.EXAMPLE
.\Clone-AzureRMresourceGroup.ps1 -ResourceGroupName 'CONTOSO' -NewResourceGroupName 'NEWCONTOSO'
Clones Resource Group CONTOSO as new resource group NEWCONTOSO into the same subscription, in the same location/region and environment
.EXAMPLE
.\Clone-AzureRMresourceGroup.ps1 -ResourceGroupName 'CONTOSO' -NewResourceGroupName 'NEWCONTOSO' -NewLocation 'westus' -resume
Clones Resource Group CONTOSO as new resource group NEWCONTOSO in new location West US
.EXAMPLE
.\Clone-AzureRMresourceGroup.ps1 -ResourceGroupName 'CONTOSO' -NewResourceGroupName 'NEWCONTOSO' -Environment 'AzureUSGovernment'
Clones Resource Group CONTOSO as resource group NEWCONTOSO in Azure Government
.PARAMETER -ResourceGroupName [string]
Name of resource group being copied
.PARAMETER -NewResourceGroupName [string]
Name of resource group being created
.PARAMETER -NewLocation [string]
Name of Azure location of new resource group
.PARAMETER -Environment [string]
Name of the Environment. e.g. AzureUSGovernment. Defaults to AzureCloud
.PARAMETER -resume [switch]
Resumes after the file copy
.NOTES
Original Author: https://github.com/JeffBow
------------------------------------------------------------------------
Copyright (C) 2017 Microsoft Corporation
You have a royalty-free right to use, modify, reproduce and distribute
this sample script (and/or any modified version) in any way
you find useful, provided that you agree that Microsoft has no warranty,
obligations or liability for any sample application or script files.
------------------------------------------------------------------------
#>
#Requires -Version 4.0
param(
[Parameter(Mandatory=$true)]
[string]$ResourceGroupName,
[Parameter(Mandatory=$true)]
[string]$NewResourceGroupName,
[Parameter(Mandatory=$false)]
[string]$NewLocation,
[Parameter(Mandatory=$false)]
[string]$Environment,
[Parameter(Mandatory=$false)]
[switch]$resume
)
$resourceGroupVmResumePath = "$env:TEMP\$resourcegroupname.resourceGroupVMs.resume.json"
$resourceGroupVmSizeResumePath = "$env:TEMP\$resourcegroupname.resourceGroupVMsize.resume.json"
$VHDstorageObjectsResumePath = "$env:TEMP\$resourcegroupname.VHDstorageObjects.resume.json"
$jsonBackupPath = "$env:TEMP\$resourcegroupname.json"
$ProgressPreference = 'SilentlyContinue'
import-module AzureRM
if ((Get-Module AzureRM).Version -lt "6.0.1") {
Write-warning "Old version of Azure PowerShell module $((Get-Module AzureRM).Version.ToString()) detected. Minimum of 6.0.1 required. Run Update-Module AzureRM"
BREAK
}
<###############################
Get Storage Context function
################################>
function Get-StorageObject
{ param($resourceGroupName, $srcURI, $srcName)
$split = $srcURI.Split('/')
$strgDNS = $split[2]
$splitDNS = $strgDNS.Split('.')
$storageAccountName = $splitDNS[0]
# add uri and storage account name to custom PSobject
$PSobjSourceStorage = New-Object -TypeName PSObject
$PSobjSourceStorage | Add-Member -MemberType NoteProperty -Name srcStorageAccount -Value $storageAccountName
$PSobjSourceStorage | Add-Member -MemberType NoteProperty -Name srcURI -Value $srcURI
$PSobjSourceStorage | Add-Member -MemberType NoteProperty -Name srcName -Value $srcName
# retrieve storage account key and storage context
$StorageAccountKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroupName -Name $StorageAccountName).Value[0]
$StorageContext = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey
# add storage context to psObject
$PSobjSourceStorage | Add-Member -MemberType NoteProperty -Name SrcStorageContext -Value $StorageContext
# get storage account and add other attributes to psCustom object
$storageAccount = Get-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName
$PSobjSourceStorage | Add-Member -MemberType NoteProperty -Name SrcStorageEncryption -Value $storageAccount.Encryption
$PSobjSourceStorage | Add-Member -MemberType NoteProperty -Name SrcStorageCustomDomain -Value $storageAccount.CustomDomain
$PSobjSourceStorage | Add-Member -MemberType NoteProperty -Name SrcStorageKind -Value $storageAccount.Kind
$PSobjSourceStorage | Add-Member -MemberType NoteProperty -Name SrcStorageAccessTier -Value $storageAccount.AccessTier
# get storage account sku and convert to string that is required for creation
$skuName = $storageAccount.sku.Name
switch ($skuName)
{
'StandardLRS' {$skuName = 'Standard_LRS'}
'Standard_LRS' {$skuName = 'Standard_LRS'}
'StandardZRS' {$skuName = 'Standard_ZRS'}
'StandardGRS' {$skuName = 'Standard_GRS'}
'StandardRAGRS'{$skuName = 'Standard_RAGRS'}
'PremiumLRS' {$skuName = 'Premium_LRS'}
'Premium_LRS' {$skuName = 'Premium_LRS'}
default {$skuName = 'Standard_LRS'}
}
$PSobjSourceStorage | Add-Member -MemberType NoteProperty -Name SrcSkuName -Value $skuName
return $PSobjSourceStorage
} # end of Get-StorageObject function
<###############################
get available resources function
################################>
function Get-AvailableResources
{ param($resourceType, $location)
$resource = Get-AzureRmVMUsage -Location $location | Where-Object{$_.Name.value -eq $resourceType}
[int32]$availabe = $resource.limit - $resource.currentvalue
return $availabe
}
<###############################
get blob copy status
################################>
function Get-BlobCopyStatus
{ param($context, $containerName, $blobName)
if($blobName)
{
write-verbose "Checking VHD blob copy for $blobName" -verbose
$blob = Get-AzureStorageBlob -Context $context -container $containerName -Blob $blobName
}
else
{
write-verbose "Checking VHD blob copy for container $containerName" -verbose
$blob = Get-AzureStorageBlob -Context $context -container $containerName
}
do
{
$rtn = $blob | Get-AzureStorageBlobCopyState
$rtn | Select-Object Source, Status, BytesCopied, TotalBytes | Format-List
if($rtn.status -ne 'Success')
{
write-warning "VHD blob copy is not complete"
$rh = read-host "Press <Enter> to refresh or type EXIT and press <Enter> to quit copy status updates and resume later"
if(($rh.ToLower()) -eq 'exit')
{
write-output "Run script with -resume switch to continue creating VMs after file copy has completed."
BREAK
}
}
}
while($rtn.status -ne 'Success')
# exit script if user breaks out of above loop
if($rtn.status -ne 'Success'){EXIT}
}
<###############################
Copy blob function
################################>
function copy-azureBlob
{ param($srcUri, $srcContext, $destContext, $containerName)
$split = $srcURI.Split('/')
$blobName = $split[($split.count -1)]
$blobSplit = $blobName.Split('.')
$extension = $blobSplit[($blobSplit.count -1)]
if($($extension.tolower()) -eq 'status' ){Write-Output "Status file blob $blobname skipped";return}
if(! $containerName){$containerName = $split[3]}
# add full path back to blobname
if($split.count -gt 5)
{
$i = 4
do
{
$path = $path + "/" + $split[$i]
$i++
}
while($i -lt $split.length -1)
$blobName= $path + '/' + $blobName
$blobName = $blobName.Trim()
$blobName = $blobName.Substring(1, $blobName.Length-1)
}
# create container if doesn't exist
if (!(Get-AzureStorageContainer -Context $destContext -Name $containerName -ea SilentlyContinue))
{
try
{
$newRtn = New-AzureStorageContainer -Context $destContext -Name $containerName -Permission Off -ea Stop
Write-Output "Container $($newRtn.name) was created."
}
catch
{
$_ ; break
}
}
try
{
$blobCopy = Start-AzureStorageBlobCopy -ea Stop `
-srcUri $srcUri `
-SrcContext $srcContext `
-DestContainer $containerName `
-DestBlob $blobName `
-DestContext $destContext
write-output "$srcUri is being copied to $containerName"
}
catch
{
$_ ; write-warning "Failed to copy to $srcUri to $containerName"
}
} # end of copy-azureBlob function
<###############################
Read resource group from old Sub
################################>
# Verify specified Environment
if($Environment -and (Get-AzureRMEnvironment -Name $Environment) -eq $null)
{
write-warning "The specified -Environment could not be found. Specify one of these valid environments."
$Environment = (Get-AzureRMEnvironment | Select-Object Name, ManagementPortalUrl | Out-GridView -title "Select a valid Azure environment for your subscription" -OutputMode Single).Name
}
# get Azure creds for source
write-host "Enter credentials for your Azure Subscription..." -f Yellow
if($Environment)
{
$login= Connect-AzureRmAccount -EnvironmentName $Environment
}
else
{
$login= Connect-AzureRmAccount
}
$loginID = $login.context.account.id
$sub = Get-AzureRmSubscription
$SubscriptionId = $sub.Id
# check for multiple subs under same account and force user to pick one
if($sub.count -gt 1)
{
$SubscriptionId = (Get-AzureRmSubscription | Select-Object * | Out-GridView -title "Select Target Subscription" -OutputMode Single).Id
Select-AzureRmSubscription -SubscriptionId $SubscriptionId | Out-Null
$sub = Get-AzureRmSubscription -SubscriptionId $SubscriptionId
}
# check for valid sub
if(! $SubscriptionId)
{
write-warning "The provided credentials failed to authenticate or are not associcated to a valid subscription. Exiting the script."
break
}
$SubscriptionName = $sub.Name
write-host "Logged into $SubscriptionName with subscriptionID $SubscriptionId as $loginID" -f Green
# check for valid source resource group
if(-not ($sourceResourceGroup = Get-AzureRmResourceGroup -ResourceGroupName $resourceGroupName))
{
write-warning "The provided resource group $resourceGroupName could not be found. Exiting the script."
break
}
if(! $resume)
{
# create export JSON for backup purposes
$RGexport = Export-AzureRmResourceGroup -ResourceGroupName $resourceGroupName -Path $jsonBackupPath -IncludeParameterDefaultValue -Force -wa SilentlyContinue
# get configuration details for different resources
[string] $location = $sourceResourceGroup.location
$resourceGroupStorageAccounts = Get-AzureRmStorageAccount -ResourceGroupName $resourceGroupName
$resourceGroupManagedDisks = Get-AzureRmDisk -ResourceGroupName $resourceGroupName
$resourceGroupVirtualNetworks = Get-AzureRmVirtualNetwork -ResourceGroupName $resourceGroupName
$resourceGroupNICs = Get-AzureRmNetworkInterface -ResourceGroupName $resourceGroupName
$resourceGroupNSGs = Get-AzureRmNetworkSecurityGroup -ResourceGroupName $resourceGroupName
$resourceGroupAvSets = Get-AzureRmAvailabilitySet -ResourceGroupName $resourceGroupName
$resourceGroupVMs = Get-AzureRMVM -ResourceGroupName $resourceGroupName
$resourceGroupPIPs = Get-AzureRmPublicIpAddress -ResourceGroupName $resourceGroupName
$resourceGroupNICs = Get-AzureRmNetworkInterface -ResourceGroupName $resourceGroupName
$resourceGroupLBs = Get-AzureRmLoadBalancer -ResourceGroupName $resourceGroupName
if(! $resourceGroupVMs){write-warning "No virtual machines found in resource group $resourceGroupName"; break}
# display what we found
write-host "The following items will be copied:" -f DarkGreen
write-host "Storage Accounts:" -f DarkGreen
$resourceGroupStorageAccounts.StorageAccountName
write-host "Managed Disks:" -f DarkGreen
$resourceGroupManagedDisks.Name
write-host "Virtual Machines:" -f DarkGreen
$resourceGroupVMs.name
write-host "Operating system disks:" -f DarkGreen
$resourceGroupVMs.storageProfile.osdisk.name
write-host "Data disks:" -f DarkGreen
$resourceGroupVMs.datadisknames
# check to make sure VMs are not running
write-host "Current status of VMs:" -f DarkGreen
$resourceGroupVMs | %{
$status = ((get-azurermvm -ResourceGroupName $resourceGroupName -Name $_.name -status).Statuses|Where-Object{$_.Code -like 'PowerState*'}).DisplayStatus
write-output "$($_.name) status is $status"
if($status -eq 'VM running')
{
write-warning "All virtual machines in this resource group are not stopped. Please stop all VMs and try again"
break
}
}
write-host "Virtual networks:" -f DarkGreen
$resourceGroupVirtualNetworks.name
write-host "Network Security Groups:" -f DarkGreen
$resourceGroupNSGs.name
write-host "Load Balancers:" -f DarkGreen
$resourceGroupLBs.name
write-host "Public IPs:" -f DarkGreen
$resourceGroupPIPs.name
# create array of custom PSobjects that contain storage account details and security context for each VHD that is found
# this is consumed later during the copy process after you log into the target subscription
[array]$sourceVHDstorageObjects = $()
write-verbose "Retrieving storage context for each source blob" -Verbose
foreach($vm in $resourceGroupVMs)
{
# get blob storage account name from VM.URI
if($vm.storageprofile.osdisk.vhd)
{
$vmURI = $vm.storageprofile.osdisk.vhd.uri
$obj = $null
$obj = Get-StorageObject -resourceGroupName $resourceGroupName -srcURI $vmURI -srcName $vm.storageprofile.osdisk.Name -srcAccountType 'NULL'
[array]$sourceVHDstorageObjects += $obj
}
if($vm.storageProfile.datadisks)
{
foreach($disk in $vm.storageProfile.datadisks)
{
if($disk.vhd)
{
$diskURI = $disk.vhd.uri
$obj = $null
$obj = Get-StorageObject -resourceGroupName $resourceGroupName -srcURI $diskURI -srcName $disk.Name
[array]$sourceVHDstorageObjects += $obj
}
}
}
}
[array]$sourceStorageObjects = $()
#get any storage accounts and blobs that were not VHDs attached to VMs
foreach($sourceStorageAccount in $resourceGroupStorageAccounts)
{
$sourceStorageAccountName = $sourceStorageAccount.StorageAccountName
$sourceStorageAccountKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroupName -Name $sourceStorageAccountName).Value[0]
$sourceStorageContext = New-AzureStorageContext -StorageAccountName $sourceStorageAccountName -StorageAccountKey $sourceStorageAccountKey
$sourceStorageContainers = Get-AzureStorageContainer -Context $sourceStorageContext
foreach($container in $sourceStorageContainers)
{
$blobs = Get-AzureStorageBlob -Container $container.name -Context $sourceStorageContext
foreach($blob in $blobs)
{
# get storage account details from uri
$URI = $blob.ICloudBlob.uri.Absoluteuri
# only add to sourceStorageObjects if it isn't in sourceVHDstorageObjects - must do replace to adapt to absoluteURI
if($sourceVHDstorageObjects.srcURI -notcontains ($URI.replace('https','http')) -and $sourceVHDstorageObjects.srcURI -notcontains $URI)
{
$obj = $null
$obj = Get-StorageObject -resourceGroupName $resourceGroupName -srcURI $URI -srcName $blob.Name
[array]$sourceStorageObjects += $obj
}
}
}
}
write-host "Additional storage blobs:" -f DarkGreen
$sourceStorageObjects.srcURI
<###############################
Create new Resource Group
################################>
$ResourceGroupName = $NewResourceGroupName
<###############################
Verify Location
################################>
if($NewLocation)
{
$srcLocation = $location
$location = $NewLocation
Write-Output "Verifying specified location: $location ..."
# Prompt for location if provided location doesn't exist in current environment.
$location = (Get-AzureRMlocation | Where-Object { $_.Providers -eq 'Microsoft.Compute' -and ( $_.DisplayName -like $location -or $_.location -like $location)}).location
if(! $location)
{
write-warning "$NewLocation is an invalid Azure Resource Group location for this environment. Please select a valid location and click OK"
$location = (Get-AzureRMlocation | Where-Object { $_.Providers -eq 'Microsoft.Compute'} | Select-Object DisplayName, Providers | Out-GridView -Title "Select Azure Resource Group Location" -OutputMode Single).location
}
}
<###############################
Verify Available Resources
################################>
foreach ($vmSize in ($resourceGroupVMs.hardwareprofile.vmsize))
{
$cores = $null
$cores = (Get-AzureRmVMSize -Location $location | Where-Object{$_.Name -eq $vmSize}).NumberOfCores
$totalCoresNeeded = $cores + $totalCoresNeeded
}
$TotalAvailabeVMs = Get-availableResources -ResourceType 'virtualMachines' -Location $location
if($resourceGroupVMs.count -gt $TotalAvailabeVMs){Write-Warning "Insufficent available VMs in location $location. Script halted."; break}
$TotalAvailabeCores = Get-availableResources -ResourceType 'cores' -Location $location
if($totalCoresNeeded -gt $TotalAvailabeCores){Write-Warning "Insufficent available cores in location $location. Script halted."; break}
$TotalAvailabeAVs = Get-availableResources -ResourceType 'availabilitySets' -Location $location
if($resourceGroupAvSets.count -gt $TotalAvailabeAVs){Write-Warning "Insufficent Availability Sets in location $location. Script halted."; break}
<###############################
Validate and create new resource group
################################>
do
{
$RGexists = $null
try
{
$RGexists = Get-AzureRmResourceGroup -Name $ResourceGroupName -ea stop
}
catch{}
if($RGexists)
{
write-warning "$ResourceGroupName already exists."
$ResourceGroupName = read-host 'Enter a different Resource Group Name'
}
}
while($RGexists)
try
{
write-verbose "Creating new resource group $resourceGroupName in $location" -Verbose
$NewResourceGroup = New-AzureRmResourceGroup -Name $ResourceGroupName -Location $location -ea Stop -wa SilentlyContinue
write-output "The new resource group $resourceGroupName was created in subscription $SubscriptionName"
}
catch
{
$_
write-warning "The new resource group $resourceGroupName was not created. Exiting the script."
break
}
<###############################
Create new destination storage accounts
and copy blobs
################################>
# initialize array to store new destination storage account names relative to srcURI
[array]$VHDstorageObjects = @()
# get all the unique source storage accounts from custom psobject
$srcStorageAccountNames = $sourceStorageObjects | Select-Object -Property srcStorageAccount -Unique
$VHDsrcStorageAccounts = $sourceVHDstorageObjects| Select-Object -Property srcStorageAccount -Unique
# add the VHD storage accounts to $sourceStorageObjects if they're not there already
foreach($VHDsrcStorageAccountObj in $VHDsrcStorageAccounts)
{
$VHDsrcStorageAccountName = $VHDsrcStorageAccountObj.srcStorageAccount
if($srcStorageAccountNames.srcStorageAccount -notcontains $VHDsrcStorageAccountName )
{
[array]$sourceStorageObjects += $sourceVHDstorageObjects|Where-Object{$_.srcStorageAccount -eq $VHDsrcStorageAccountName}
}
}
$srcStorageAccounts = $sourceStorageObjects | Select-Object -Property srcStorageAccount -Unique
# process each source storage account - creating new destination storage account from old account name
foreach($srcStorageAccountObj in $srcStorageAccounts)
{
$srcStorageAccount = $srcStorageAccountObj.srcStorageAccount
# create unique storage account name from old account name and guid
if($srcStorageAccount.Length -gt 16){$first16 = $srcStorageAccount.Substring(0,16)}else{$first16 = $srcStorageAccount}
[string] $guid = (New-Guid).Guid
[string] $DeststorageAccountName = "$($first16.ToLower())"+($guid.Substring(0,8))
# select sku and other attributes
$skuName = ($sourceStorageObjects | Where-Object{$_.srcStorageAccount -eq $srcStorageAccount} | Select-Object -Property srcSkuName -Unique).srcSkuName
$Encryption = ($sourceStorageObjects | Where-Object{$_.srcStorageAccount -eq $srcStorageAccount} | Select-Object -Property SrcStorageEncryption -Unique).SrcStorageEncryption
$CustomDomain = ($sourceStorageObjects | Where-Object{$_.srcStorageAccount -eq $srcStorageAccount} | Select-Object -Property SrcStorageCustomDomain -Unique).SrcStorageCustomDomain
$kind = ($sourceStorageObjects | Where-Object{$_.srcStorageAccount -eq $srcStorageAccount} | Select-Object -Property SrcStorageKind -Unique).SrcStorageKind
$AccessTier = ($sourceStorageObjects | Where-Object{$_.srcStorageAccount -eq $srcStorageAccount} | Select-Object -Property SrcStorageAccessTier -Unique).SrcStorageAccessTier
$storageParams = @{
"ResourceGroupName" = $resourceGroupName
"Name" = $DeststorageAccountName
"location" = $location
"SkuName" = $skuName
}
# add AccessTier if kind is BlobStorage.
if($kind -ne 'Storage')
{
$storageParams.Add("Kind", $kind)
$storageParams.Add("AccessTier", $accessTier)
}
# add CustomDomainName if present.
if($CustomDomain)
{
$storageParams.Add("CustomDomainName", $CustomDomain)
}
# add CustomDomainName if present.
if($Encryption)
{
if($Encryption.Services.Blob){$encryptionBlob = 'Blob'}
if($Encryption.Services.File){$encryptionFile = 'File'}
if($encryptionBlob){$EncryptionType = $encryptionBlob}
if($encryptionFile){$EncryptionType = $encryptionFile}
if($encryptionBlob -and $encryptionFile){$EncryptionType = "$encryptionBlob,$encryptionFile"}
# Remarked for newer modules. This was required prior to AzureRM.Storage 5.0.2
# $storageParams.Add("EnableEncryptionService", $EncryptionType)
}
# Create new storage account
do
{
try
{
# create new storage account
write-verbose "Creating storage account $DeststorageAccountName in resource group $resourceGroupName at location $location" -verbose
$newStorageAccount = New-AzureRmStorageAccount @storageParams -ea Stop -wa SilentlyContinue
write-output "The storage account $DeststorageAccountName was created"
}
catch
{
$_
write-warning "Failed to create storage account. Storage account name $DeststorageAccountName may already exists."
$DeststorageAccountName = read-host 'Enter a different Destination Storage Account Name'
}
}
while(! $newStorageAccount)
try
{
# get key and storage context of newly created storage account
$DestStorageAccountKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroupName -Name $DestStorageAccountName -ea Stop).Value[0]
$DestStorageContext = New-AzureStorageContext -StorageAccountName $DestStorageAccountName -StorageAccountKey $DestStorageAccountKey -ea Stop -wa SilentlyContinue
}
catch
{
write-warning "Could not retrieve storage account key or storage context for $DestStorageAccountName . Exiting the script."
break
}
# start blob copy for VHDs attached to VMs
foreach($obj in $sourceVHDstorageObjects | Where-Object{$_.srcStorageAccount -eq $srcStorageAccount})
{
$srcURI = $obj.srcURI
copy-azureBlob -srcUri $srcURI -srcContext $obj.SrcStorageContext -destContext $DestStorageContext
# add srcURI and destination storage account name to custom PSobject
$PSobjVHDstorage = New-Object -TypeName PSObject
$PSobjVHDstorage | Add-Member -MemberType NoteProperty -Name srcName -Value $obj.srcName
$PSobjVHDstorage | Add-Member -MemberType NoteProperty -Name destStorageContext -Value $DestStorageContext
$PSobjVHDstorage | Add-Member -MemberType NoteProperty -Name srcURI -Value $srcURI
$PSobjVHDstorage | Add-Member -MemberType NoteProperty -Name srcSkuName -Value 'NULL'
[array]$VHDstorageObjects += $PSobjVHDstorage
}
# start copy for remaining blobs
if($srcStorageAccountNames)
{
foreach($obj in $sourceStorageObjects | Where-Object{$_.srcStorageAccount -eq $srcStorageAccount})
{
copy-azureBlob -srcUri $obj.srcURI -srcContext $obj.SrcStorageContext -destContext $DestStorageContext
}
}
} # end of foreach srcStorageAccounts
# create temporary blob storage account to stage managed disks that will be copied
if($newLocation -and $location -ne $srcLocation -and $resourceGroupManagedDisks)
{
if($resourceGroupName.Length -gt 16){$first16 = $resourceGroupName.Substring(0,16)}else{$first16 = $resourceGroupName }
[string] $guid = (New-Guid).Guid
[string] $tempStorageAccountName = "$($first16.ToLower())"+($guid.Substring(0,8))
$storageParams = @{
"ResourceGroupName" = $resourceGroupName
"Name" = $tempstorageAccountName
"location" = $location
"SkuName" = 'Standard_LRS'
}
# Create new storage account
do
{
try
{
# create new storage account
write-verbose "Creating temmporary storage account $tempstorageAccountName in resource group $resourceGroupName at location $location" -verbose
$newStorageAccount = New-AzureRmStorageAccount @storageParams -ea Stop -wa SilentlyContinue
write-output "The storage account $tempstorageAccountName was created"
}
catch
{
$_
write-warning "Failed to create temporary storage account. Storage account name $DeststorageAccountName may already exists."
$tempstorageAccountName = read-host 'Enter a different Temporary Storage Account Name. This is used to stage managed disks.'
}
}
while(! $newStorageAccount)
try
{
# get key and storage context of newly created storage account
$tempStorageAccountKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroupName -Name $tempStorageAccountName -ea Stop).Value[0]
$tempStorageContext = New-AzureStorageContext -StorageAccountName $tempStorageAccountName -StorageAccountKey $tempStorageAccountKey -ea Stop -wa SilentlyContinue
$tempContainer = New-AzureStorageContainer -Name 'vhdblobs' -Context $tempStorageContext -Permission Blob -ea Stop -wa SilentlyContinue
}
catch
{
write-warning "Could not retrieve storage account key or storage context for $tempStorageAccountName . Exiting the script."
break
}
}
# start copy of all Managed Disks
foreach($md in $resourceGroupManagedDisks)
{
$srcMDname = $md.Name
$srcSkuName = $md.Sku.Name.ToString()
$srcMDid = $md.id
# $srcOStype = $md.OsType
if($newLocation -and $location -ne $srcLocation)
{
#Get the SAS URL of the VHD blob and do a copy process to the temp storage account if the MD is out of region
$AccessURI = $md | Grant-AzureRmDiskAccess -Access 'Read' -DurationInSecond 10800
$AccessSAS = $AccessURI.AccessSAS
$rtn = Start-AzureStorageBlobCopy -AbsoluteUri $AccessSAS -DestBlob $srcMDname -DestContainer $tempContainer.Name -destContext $tempStorageContext
$PSobjVHDstorage = New-Object -TypeName PSObject
$PSobjVHDstorage | Add-Member -MemberType NoteProperty -Name srcName -Value $srcMDname
$PSobjVHDstorage | Add-Member -MemberType NoteProperty -Name destStorageContext -Value $tempStorageContext
$PSobjVHDstorage | Add-Member -MemberType NoteProperty -Name srcURI -Value $rtn.ICloudBlob.Uri.AbsoluteUri
$PSobjVHDstorage | Add-Member -MemberType NoteProperty -Name srcSkuName -Value $srcSkuName
[array]$VHDstorageObjects += $PSobjVHDstorage
}
else
{
# if it isn't a new location/region, use New-AzureRmDiskConfig -CreateOption Copy and the resource ID of the source MD
# instead of doing a blob copy of the VHD from the SAS URL
write-verbose "Creating new managed disk $srcMDname in $location" -Verbose
try
{
$mdiskconfig = New-AzureRmDiskConfig -SkuName $srcSkuName -Location $location -CreateOption Copy -SourceResourceId $srcMDid
$newMDdisk = New-AzureRmDisk -ResourceGroupName $resourceGroupName -Disk $mdiskconfig -DiskName $srcMDname
write-output "The managed disk $srcMDname was created."
}
catch
{
$_
write-warning "Failed to create new managed disk $srcMDname"
}
}
}
<###############################
Create new network resources.
Vnets, NICs, Loadbalancers, PIPs
################################>
# create new Network Security Groups
foreach($srcNSG in $resourceGroupNSGs)
{
$nsgName = $srcNSG.name
[array]$nsgRules = @()
foreach($nsgRule in $srcNSG.SecurityRules)
{
$nsgRuleParams = @{
"Name" = $nsgRule.Name
"Access" = $nsgRule.Access
"Protocol" = $nsgRule.Protocol
"Direction" = $nsgRule.Direction
"Priority" = $nsgRule.Priority
"SourceAddressPrefix" = $nsgRule.SourceAddressPrefix
"SourcePortRange" = $nsgRule.SourcePortRange
"DestinationAddressPrefix" = $nsgRule.DestinationAddressPrefix
"DestinationPortRange" = $nsgRule.DestinationPortRange
}
if($nsgRule.Description)
{
$nsgRuleParams.Add("Description", $nsgRule.Description)
}
$nsgRules += New-AzureRmNetworkSecurityRuleConfig @nsgRuleParams
}
try
{
write-verbose "Creating Network Security Group $nsgName in resource group $resourceGroupName at location $location" -verbose
$NSG = New-AzureRmNetworkSecurityGroup -Name $nsgName -SecurityRules $nsgRules -ResourceGroupName $ResourceGroupName -Location $location -ea Stop -wa SilentlyContinue
Write-Output "Network Security Group $nsgName was created"
}
catch
{
$_
write-warning "Failed to create Network Security Group $nsgName"
}
}
# create new Virtual Network(s)
foreach($srcNetwork in $resourceGroupVirtualNetworks)
{
$destVNname = $srcNetwork.Name
$destAddressPrefix = $srcNetwork.AddressSpace.AddressPrefixes
$destDNSserver = $srcNetwork.DhcpOptions.DnsServers
$destSubnets = $srcNetwork.Subnets
try
{
write-verbose "Creating virtual network $destVNname in resource group $resourceGroupName at location $location" -verbose
$newVirtualNetwork = New-AzureRmVirtualNetwork -Name $destVNname -ResourceGroupName $resourceGroupName -Location $location -AddressPrefix $destAddressPrefix -DnsServer $destDNSserver -Subnet $destSubnets -Force -ea Stop -wa SilentlyContinue
Write-Output "Virtual Network $destVNname was created"
}
catch
{
$_
write-warning "Failed to create virtual network $destVNname"
}
foreach($destSub in $destSubnets)
{
if($destSub.Subnets.NetworkSecurityGroup)
{
try
{
$NSGsplit = $destSub.Subnets.NetworkSecurityGroup.id.split('/')
$srcNSGname = $NSGsplit[$NSGsplit.Length -1]
$NSG = Get-AzureRmNetworkSecurityGroup -Name $srcNSGname -ResourceGroupName $ResourceGroupName -ea Stop
$subnet = $newVirtualNetwork | Get-AzureRmVirtualNetworkSubnetConfig -Name $destSub.Name -ea Stop -wa SilentlyContinue
Set-AzureRmVirtualNetworkSubnetConfig -VirtualNetwork $newVirtualNetwork -Name $destSub.Name -AddressPrefix $subnet.AddressPrefix -NetworkSecurityGroup $NSG | Set-AzureRmVirtualNetwork -ea Stop | out-null
}
catch
{
$_
write-warning "Failed to add Network Security Group $srcNSGname to $($destSub.Name)"
}
}
}
}
# create new Availability sets
foreach($srcAVset in $resourceGroupAvSets)
{
$AVname = $srcAVset.name
$avParams = @{
"Name" = $AVname
"ResourceGroupName" = $resourceGroupName
"Location" = $location
"sku" = $srcAVset.Sku
"PlatformFaultDomainCount" = $srcAVset.PlatformFaultDomainCount
"PlatformUpdateDomainCount" = $srcAVset.PlatformUpdateDomainCount
"ea" = 'Stop'
"wa" = 'SilentlyContinue'
}
# deprecated in newer module versions
#if($srcAVset.Managed)
#{
# $avParams.Add("Managed", $srcAVset.Managed)
#}
try
{
write-verbose "Creating availability set $AVname in resource group $resourceGroupName at location $location" -verbose
$NewAvailabilitySet = New-AzureRmAvailabilitySet @avParams
Write-Output "Availability Set $AVname was created"
}
catch
{
$_
write-warning "Failed to create availability set $AVname"
}
}
# create new PIPs
foreach($srcPIP in $resourceGroupPIPs)
{
$pipName = $srcPIP.name
$pipDomainNameLabel = $srcPIP.dnssettings.domainNameLabel
$pipParams = @{
"Name" = $pipName
"ResourceGroupName" = $resourceGroupName
"Location" = $location
"AllocationMethod" = $srcPIP.PublicIpAllocationMethod
"ea" = 'Stop'
"wa" = 'SilentlyContinue'
}
# append 'new' to name so it is unique from existing
if($pipDomainNameLabel)
{
$NewPipDomainNameLabel = $pipDomainNameLabel + 'new'
$pipParams.Add("DomainNameLabel", $NewPipDomainNameLabel)
}
try
{
write-verbose "Creating public IP $pipName in resource group $resourceGroupName at location $location" -verbose
$PIP = New-AzureRmPublicIpAddress @pipParams
Write-Output "Public IP $pipName was created with DomainName Label $NewPipDomainNameLabel"
}
catch
{
$_
write-warning "Failed to create Public IP $pipName"
}
}
# create new Load Balancer
foreach($srcLB in $resourceGroupLBs)
{
$LBName = $srcLB.name
$LBFrontendIpConfigurations = $srcLB.FrontendIpConfigurations
$LBInboundNatRules = $srcLB.InboundNatRules
$LBBackendAddressPool = $srcLB.BackendAddressPools
$LBProbe = $srcLB.Probes
$LoadBalancingRule = $srcLB.LoadBalancingRules
$LBInboundNatPool = $srcLB.InboundNatPools
$subnet = $null
$vnet = $null
# add IP Configs
[array]$newLBipConfigs = @()
foreach($LBipConfig in $LBFrontendIpConfigurations)
{
$newLBipConfig = $null
$LBipConfigName = $LBipConfig.name
$lbConfigParams = @{"Name"= $LBipConfigName}
# get new vnet and subnet from old vnet and subnet names
if($LBipConfig.Subnet)
{
$subsplit = $LBipConfig.Subnet.id.split('/')
$subnetName = $subsplit[$subsplit.Length -1]
$vnetName = $subsplit[$subsplit.Length -3]
$subnet = $null
$vnet = $null
try
{
$vnet = Get-AzureRmVirtualNetwork -name $vnetName -ResourceGroupName $resourceGroupName -ea Stop -wa SilentlyContinue
$subnet = $vnet | Get-AzureRmVirtualNetworkSubnetConfig -Name $subnetName -ea Stop -wa SilentlyContinue
}
catch{}
$lbConfigParams.Add("SubnetId", $subnet.id)
}
# add PublicIpAddress if present.
if($LBipConfig.PublicIpAddress)
{
$lbPubIPSplit = $LBipConfig.PublicIpAddress.id.split('/')
$lbPubIPName = $lbPubIPSplit[$lbPubIPSplit.Length -1]
try
{
$lbPubIP = Get-AzureRmPublicIpAddress -Name $lbPubIPName -ResourceGroupName $resourceGroupName -ea Stop -wa SilentlyContinue
}
catch{}
if($lbPubIP)
{
$lbConfigParams.Add("PublicIpAddress", $lbPubIP)