-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathrgcopy.ps1
20830 lines (18000 loc) · 590 KB
/
rgcopy.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
<#
rgcopy.ps1: Copy Azure Resource Group
version: 0.9.66
version date: December 2024
Author: Martin Merdes
Public Github: https://github.com/Azure/RGCOPY
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
#>
#Requires -Version 7.2 -Modules 'Az.Accounts', 'Az.Compute', 'Az.Storage', 'Az.Network', 'Az.Resources'
# by default, Parameter Set 'dualRG' is used
[CmdletBinding( DefaultParameterSetName='dualRG',
HelpURI="https://github.com/Azure/RGCOPY/blob/main/rgcopy-docu.md")]
param (
#--------------------------------------------------------------
# essential parameters
#--------------------------------------------------------------
# parameter is always mandatory
[Parameter(Mandatory=$True)]
[string] $sourceRG # Source Resource Group
# parameter is mandatory, dependent on used Parameter Set
,[Parameter(Mandatory=$False,ParameterSetName='singleRG')]
[Parameter(Mandatory=$True, ParameterSetName='dualRG')]
[string] $targetRG # Target Resource Group (will be created)
,[switch] $allowExistingDisks # do not check whether the targetRG already contains disks
# parameter is mandatory, dependent on used Parameter Set
,[Parameter(Mandatory=$False,ParameterSetName='singleRG')]
[Parameter(Mandatory=$True, ParameterSetName='dualRG')]
[string] $targetLocation # Target Region
# storage account
,[string] $targetSA # only needed if calculated name is not unique in subscription (= ANF account name)
,[string] $sourceSA # only needed if calculated name is not unique in subscription
# subscriptions and User
,[string] $sourceSub # Source Subscription display name
,[string] $sourceSubUser # User Name
,[string] $sourceSubTenant # Tenant Name (optional)
,[string] $targetSub # Target Subscription display name
,[string] $targetSubUser # User Name
,[string] $targetSubTenant # Tenant Name (optional)
#--------------------------------------------------------------
# parameters for Copy Mode
#--------------------------------------------------------------
# operation switches
,[switch] $skipArmTemplate # skip ARM template creation
,[switch] $skipSnapshots # skip snapshot creation of disks and volumes (in sourceRG)
,[switch] $stopVMsSourceRG # stop VMs in the source RG before creating snapshots
,[switch] $skipBackups # skip backup of files (in sourceRG)
,[switch] $skipDeployment # skip deployment (in targetRG)
,[switch] $skipDeploymentVMs # skip part step: deploy Virtual Machines
,[switch] $skipRestore # skip part step: restore files
,[switch] $stopRestore # run all steps until (excluding) Restore
,[switch] $continueRestore # run Restore and all later steps
,[switch] $startWorkload # start workload
,[switch] $stopVMsTargetRG # stop VMs in the target RG after deployment
,[switch] $deleteSnapshots # delete snapshots after deployment
,[switch] $deleteSourceSA # delete storage account in the source RG after deployment
,[switch] $deleteTargetSA # delete storage account in the target RG after deployment
# simulating
,[switch] $simulate # just create ARM template
# VM extensions
,[switch] $skipExtensions # do not install VM extensions
,[switch] $autoUpgradeExtensions # auto upgrade VM extensions
,$installExtensionsSapMonitor = @() # Array of VMs where SAP extension should be installed
,[string] $diagSettingsPub = 'PublicSettings.json'
,[string] $diagSettingsProt = 'ProtectedSettings.json'
,[string] $diagSettingsContainer
,[string] $diagSettingsSA
# disk creation options
,[switch] $createDisksManually
,[switch] $dualDeployment
,[switch] $skipWorkarounds
,[switch] $useIncSnapshots # always use INCREMENTAL rather than FULL snapshots (even in same region and for standard disks)
,[switch] $useRestAPI # always use REST API rather than az-cmdlets when possible
,[switch] $useSnapshotCopy # always use SNAPSHOT copy (even in same region)
,[switch] $useBlobCopy # always use BLOB copy (even in same region)
,[switch] $skipRemoteCopy # skip BLOB/snapshot creation (in targetRG)
,[switch] $restartRemoteCopy # restart a failed BLOB Copy
,[string] $blobsSA # Storage Account of BLOBs
,[string] $blobsRG # Resource Group of BLOBs
,[string] $blobsSaContainer # Container of BLOBs
# parameters for cleaning an incomplete RGCOPY run
,[array] $justCopyBlobs # only copy these disks to BLOBs (from existing snapshots)
,[array] $justCopySnapshots # only copy these disks to SNAPSHOTs (from existing snapshots)
,[array] $justCopyDisks # only copy these disks (by creating snapshots and disks)
,[switch] $justStopCopyBlobs
#--------------------------------------------------------------
# parameters for Archive Mode
#--------------------------------------------------------------
,[switch] $archiveMode # create backup of source RG to BLOB, no deployment
,[string] $archiveContainer # container in storage account that is used for backups
,[switch] $archiveContainerOverwrite # allow overwriting existing archive container
#--------------------------------------------------------------
# parameters for Clone Mode
#--------------------------------------------------------------
# use Parameter Set singleRG when switch cloneMode is set
,[Parameter(ParameterSetName='singleRG')]
[switch] $cloneMode
,[int] $cloneNumber = 1
,$cloneVMs = @()
,$attachVmssFlex = @()
,$attachAvailabilitySet = @()
,$attachProximityPlacementGroup = @()
# ,$setVmZone = @()
# ,$setVmFaultDomain = @()
# ,$setVmName = @()
# ,[switch] $renameDisks # rename all disks using their VM name
#--------------------------------------------------------------
# parameters for Merge Mode
#--------------------------------------------------------------
,[Parameter(ParameterSetName='singleRG')]
[switch] $mergeMode
,$setVmMerge = @()
# usage: $setVmMerge = @("$net/$subnet@$vm1,$vm2,...", ...)
# with $net as virtual network name, $subnet as subnet name in target resource group
# merge VM jumpbox into target RG: @("vnet/default@jumpbox")
# ,$attachVmssFlex = @() # parameter also available in Clone Mode, see above
# ,$attachAvailabilitySet = @() # parameter also available in Clone Mode, see above
# ,$attachProximityPlacementGroup = @() # parameter also available in Clone Mode, see above
# ,$setVmZone = @()
# ,$setVmFaultDomain = @()
# ,$setVmName = @()
#--------------------------------------------------------------
# parameters for Update Mode
#--------------------------------------------------------------
# use Parameter Set singleRG when switch updateMode is set
,[Parameter(ParameterSetName='singleRG')]
[switch] $updateMode # change properties in source RG
# ,[switch] $simulate # just simulate Updates
# ,[switch] $stopVMsSourceRG # parameter also available in Copy Mode, see above
# ,$setVmSize = @() # parameter also available in Copy Mode, see below
# ,$setDiskSize = @() # parameter also available in Copy Mode, see below
# ,$setDiskTier = @() # parameter also available in Copy Mode, see below
# ,$setDiskBursting = @() # parameter also available in Copy Mode, see below
# ,$setDiskMaxShares= @() # parameter also available in Copy Mode, see below
# ,$setDiskCaching = @() # parameter also available in Copy Mode, see below
# ,$setDiskSku = @() # parameter also available in Copy Mode, see below
# ,$setAcceleratedNetworking = @() # parameter also available in Copy Mode, see below
# ,[switch] $deleteSnapshots # parameter also available in Copy Mode, see below
,[switch] $deleteSnapshotsAll # delete all snapshots
,[string] $createBastion # create bastion. Parameter format: <addressPrefix>@<vnet>
,[switch] $deleteBastion # delete bastion
#--------------------------------------------------------------
# parameters for Patch Mode
#--------------------------------------------------------------
# use Parameter Set singleRG when switch patchMode is set
,[Parameter(ParameterSetName='singleRG')]
[switch] $patchMode # apply Linux patches
,$patchVMs = '*'
# ,$skipVMs = @()
,[switch] $patchKernel # install newest Linux kernel (and security patches)
,[switch] $patchAll # install ALL patches on VM (not only security patches)
,[string] $prePatchCommand # e.g. 'yum-config-manager --save --setopt=rhui-rhel-7-server-dotnet-rhui-rpms.skip_if_unavailable=true 1>/dev/null'
,[switch] $skipPatch
,[switch] $forceExtensions
# ,[switch] $autoUpgradeExtensions
# ,[switch] $stopVMsSourceRG
,$defaultTags = @{}
#--------------------------------------------------------------
# file locations
#--------------------------------------------------------------
,[string] $pathArmTemplate # given ARM template file
,[string] $pathArmTemplateDisks # given ARM template file for Disk creation
,[string] $pathExportFolder = '~' # default folder for all output files (log-, config-, ARM template-files)
,[string] $pathPreSnapshotScript # running before ARM template creation on sourceRG (after starting VMs and SAP)
,[string] $pathPostDeploymentScript # running after deployment on targetRG
# script location of shell scripts inside the VM
,[string] $scriptStartSapPath # if not set, then calculated from vm tag rgcopy.ScriptStartSap
,[string] $scriptStartLoadPath # if not set, then calculated from vm tag rgcopy.ScriptStartLoad
,[string] $scriptStartAnalysisPath # if not set, then calculated from vm tag rgcopy.ScriptAnalyzeLoad
#--------------------------------------------------------------
# Azure NetApp Files
#--------------------------------------------------------------
,[string] $netAppServiceLevel = 'Premium' # Service Level for NetApp Capacity Pool: 'Standard', 'Premium', 'Ultra'
,[string] $netAppAccountName # in Copy Mode: Name of new Account
,[string] $netAppPoolName # in Copy Mode: Name of new Pool
,[int] $netAppPoolGB = 4 * 1024 # in Copy Mode: Size of new Pool in GB
,[string] $netAppMovePool # in Update Mode: Only move this pool: <account>/<pool>
,[switch] $netAppMoveForce # in Update Mode: Always move pools, even when Service Level is identical
,[string] $netAppSubnet # new Subnet for NetApp Parameter format: <addressPrefix>@<vnet>
,[switch] $verboseLog # detailed output for converting NetApp or disks
,[string] $createDisksTier = 'P20' # minimum disk tier (in target RG) for converting NetApp or disks
,[int] $nfsQuotaGiB = 5120 # Quota for Azure NFS share (not NetApp!)
#--------------------------------------------------------------
# default values
#--------------------------------------------------------------
,[int] $grantTokenTimeSec = 3 * 24 * 60 * 60 # grant access to source disks for 3 days
,[int] $vmStartWaitSec = 5 * 60 # wait time after VM start before using the VMs (before trying to run any script)
,[int] $preSnapshotWaitSec = 5 * 60 # wait time after running pre-snapshot script
,[int] $vmAgentWaitMinutes = 30 # maximum wait time until VM Agent is ready
,[int] $snapshotWaitCreationMinutes = 24 * 60
,[int] $snapshotWaitCopyMinutes = 3 * 24 * 60
,[int] $maxDOP = 16 # max degree of parallelism for FOREACH-OBJECT
,[string] $setOwner = '*' # Owner-Tag of Resource Group; default: $targetSubUser
,[string] $jumpboxName = '' # create FQDN for public IP of jumpbox
,[switch] $ignoreTags # ignore rgcopy*-tags for target RG CONFIGURATION
,[switch] $copyDetachedDisks # copy disks that are not attached to any VM
#--------------------------------------------------------------
# skip resources from sourceRG
#--------------------------------------------------------------
,$skipVMs = @() # Names of VMs that will not be copied
,$skipDisks = @() # Names of DATA disks that will not be copied
,$skipSecurityRules = @('SecurityCenter-JITRule*') # Name patterns of rules that will not be copied
,$keepTags = @('rgcopy*') # Name patterns of tags that will be copied, all others will not be copied
,[switch] $skipVmssFlex # do not copy VM Scale Sets Flexible
,[switch] $skipAvailabilitySet # do not copy Availability Sets
,[switch] $skipProximityPlacementGroup # do not copy Proximity Placement Groups
,[switch] $skipBastion # do not copy Bastion
,[switch] $skipBootDiagnostics # do not create Boot Diagnostics (managed storage account)
,[switch] $skipIdentities # do not copy user assigned identities
,[switch] $skipNatGateway
#--------------------------------------------------------------
# resource configuration parameters
#--------------------------------------------------------------
,[switch] $skipVmChecks # do not double check whether VMs can be deployed in target region
,[switch] $forceVmChecks # Do not automatically change resource properties to valid values
,[switch] $skipRemoteReferences
,[switch] $skipDefaultValues # Do not use resource configuration Default Values in COPY MODE
<# parameter for changing multiple resources:
[array] $parameter = @($rule1,$rule2, ...)
with [string] $rule = "$configuration@$resourceName1,$resourceName2, ..."
with [string] $configuration = "$config1/$config2"
see examples for $setVmSize below
#>
,$setVmSize = @()
# usage: $setVmSize = @("$size@$vm1,$vm2,...", ...)
# set size for single VM: @("Standard_E32s_v3@hana1")
# set size for ALL VMs: @("Standard_E32s_v3")
# set same size for 2 VMs (1 rule): @("Standard_E32s_v3@hana1,hana2")
# set size for 2 VMs separately (2 rules): @("Standard_E32s_v3@hana1", "Standard_E16s_v3@hana2")
# set 16 CPUs for single VM and 32 for others: @("Standard_E16s_v3@hana2", "Standard_E32s_v3")
# (first rule wins)
,$setDiskSize = @()
# usage: $setDiskSize = @("$size@$disk1,$disk1,...", ...) with $size in GB
# set size of single disk to 1024 GB: @("1024/hana1data1")
,$setDiskTier = @()
# usage: $setDiskTier = @("$tier@$disk1,$disk1,...", ...)
# with $tier -in ('P1', 'P2', ...) P0 for remove tier
# set tier of single disk to P40: @("P40/hana1data1")
,$setDiskBursting = @()
# usage: $setDiskBursting = @("$bursting@$disk1,$disk1...", ...)
# with $bursting -in ('True','False')
,$setDiskIOps = @()
,$setDiskMBps = @()
,$setDiskMaxShares= @()
# usage: $setDiskMaxShares = @("$maxShares@$disk1,$disk1...", ...)
# with $maxShares -in (1,2,3,...)
,$setDiskCaching = @()
# usage: $setDiskCaching = @("$caching/$writeAccelerator@$disk1,$disk1...", ...)
# with $caching -in @('ReadOnly','ReadWrite','None')
# $writeAccelerator -in ('True','False')
# turn off writeAccelerator for all disks: @("/False")
# turn off all caches for all disks: @("None/False")
# set caching for 2 disks: @("ReadOnly/True@hana1data1", "None/False@hana1os",)
# turn on WA for one disk and off for all others: @("ReadOnly/True@hana1data1", "None/False")
,$setDiskSku = 'Premium_LRS' # default value in COPY MODE
# usage: $setDiskSku = @("$sku@$disk1,$disk1,...", ...)
# with $sku -in ('Premium_LRS','StandardSSD_LRS','Standard_LRS','Premium_ZRS','StandardSSD_ZRS')
,$setVmZone = 0 # default value in COPY MODE
# usage: $setVmZone = @("$zone@$vm1,$vm2,...", ...)
# with $zone in {none,1,2,3}
# remove zone from all VMs '0' or 'none'
# set zone 1 for 2 VMs (hana 1 and hana2) @("1@hana1,hana2")
,$setVmFaultDomain = @()
# usage: $setVmFaultDomain = @("$fault@$vm1,$vm2,...", ...)
# with $fault in {none,0,1,2}
# 'none' means: remove Fault Domain configuration from the VM
,$createVmssFlex = @()
# usage: $createVmssFlex = @("$vmss/$fault$/$zones@$vm1,$vm2,...", ...)
# with $vmss: name of VM Scale Set Flexible
# $zones: Allowed Zones in {none, 1, 2, 3, 1+2, 1+3, 2+3, 1+2+3}
# $fault: Fault domain count in in {none, 1, 2, 3, max}
,$singlePlacementGroup # in {Null, True, False}
,$createAvailabilitySet = @()
# usage: $createAvailabilitySet = @("$avSet/$fd/$ud$@$vm1,$vm2,...", ...)
# with $avSet: name of AvailabilitySet
# $fd: faultDomainCount
# $ud: updateDomainCount
# create AvSet with name 'asname' for 2 VMs (hana 1 and hana2): @("asname/2/5@hana1,hana2")
# see also parameter $skipAvailabilitySet
,$createProximityPlacementGroup = @()
# usage: $createProximityPlacementGroup = @("$ppg@$vm1,$vm2,...", ...)
# with $ppg: [string]
# $vm: ether name of VM or name of AvSet
# sets ppg with name 'ppgname' for 2 VMs (hana 1 and hana2): @("ppgname@hana1,hana2")
# creates Proximity Placement Group 'ppgname'
# see also parameter $skipProximityPlacementGroup
,$createVolumes = @()
# defines NetApp volumes for the target RG
# usage: $createVolumes = @("$size@$mp1,$mp2,...", ...)
# with $size: volume size in GB (>= 100)
# with $mp = $vmName/$pathToMountPoint
,$createDisks = @()
# defines additional disks for the target RG
# usage: $createDisks = @("$size@$mp1,$mp2,...", ...)
# with $size: disk size in GB (>= 1)
# with $mp = $vmName/$pathToMountPoint
,$snapshotVolumes = @()
# creates NetApp volume snapshots in the source RG
# usage: $snapshotVolumes = @("$rg/$account/$pool@$vol1,$vol2,...", ...)
# or: $snapshotVolumes = @("$account/$pool@$vol1,$vol2,...", ...)
# with $rg: resource group name (default: $sourceRG) of NetApp account
# with $account: NetApp account name
# with $pool: NetApp pool name
# with $vol: NetApp volume name
,$setVmDeploymentOrder = @()
# deploy (start) VMs in specific order
# usage: $setVmDeploymentOrder = @("$prio@$vm1,$vm2,...", ...)
# with $prio -in (1,2,3,...)
# example with multiple priorities: @("1@AdVM", "2@iscsi", "3@sofs1,sofs2", "4@hana1,hana2")
,$setPrivateIpAlloc = 'Static' # default value in COPY MODE
# usage: $setPrivateIpAlloc = @("$allocation@$ipName1,$ipName12,...", ...)
# with $allocation -in @('Dynamic', 'Static')
,$removeFQDN = $True # this default value is ALWAYS used
# removes Full Qualified Domain Name from public IP address
# usage: $removeFQDN = @("bool@$ipName1,$ipName12,...", ...)
# with $bool -in @('True')
,$setAcceleratedNetworking = $True # default value in COPY MODE
# usage: $setAcceleratedNetworking = @("$bool@$nic1,$nic2,...", ...)
# with $bool -in @('True', 'False')
,$setVmName = @()
# renames VM resource name (not name on OS level)
# usage: $setVmName = @("$vmNameNew@$vmNameOld", ...)
# set VM name dbserver for VM hana (=rename hana) @("dbserver@hana")
,$swapSnapshot4disk = @()
,$swapDisk4disk = @()
,[switch] $renameDisks # rename all disks using their VM name
#--------------------------------------------------------------
# other parameter
#--------------------------------------------------------------
,[switch] $ultraSSDEnabled # create VM with property ultraSSDEnabled even when not needed
,[boolean] $useBicep = $True
# use Parameter Set singleRG when switch justCreateSnapshots is set
,[Parameter(ParameterSetName='singleRG')]
[switch] $justCreateSnapshots
# use Parameter Set singleRG when switch justDeleteSnapshots is set
,[Parameter(ParameterSetName='singleRG')]
[switch] $justDeleteSnapshots
,$defaultDiskZone
,$defaultDiskName
#--------------------------------------------------------------
# experimental parameters: DO NOT USE!
#--------------------------------------------------------------
,[string] $monitorRG
,$setVmTipGroup = @()
,$setGroupTipSession = @()
,[string] $setIpTag
,[string] $setIpTagType = 'FirstPartyUsage'
,[switch] $allowRunningVMs
,[switch] $skipGreenlist
,[switch] $skipStartSAP
,$generalizedVMs = @()
,$generalizedUser = @()
,$generalizedPasswd = @() # will be checked below for data type [SecureString] or [SecureString[]]
,[switch] $hostPlainText
,[switch] $updateBicep
,[switch] $useNewVmSizes
# not used anymore
,[int] $waitBlobsTimeSec = 5 * 60
)
#--------------------------------------------------------------
# For debugging, you need $ErrorActionPreference = 'Continue'
# Therefore, use:
#
# set-Item 'Env:\ErrorActionPreference' 'Continue'
#
# For normal use, you need $ErrorActionPreference = 'Stop'
# Hereby, any exception can be caugth by RGCOPY
#--------------------------------------------------------------
$pref = (get-Item 'Env:\ErrorActionPreference' -ErrorAction 'SilentlyContinue').value
if ($Null -ne $pref ) { $ErrorActionPreference = $pref }
else { $ErrorActionPreference = 'Stop' }
$boundParameterNames = $PSBoundParameters.keys
# general parameters
$configParameters = @(
'snapshotVolumes'
'createVolumes'
'createDisks'
'setVmDeploymentOrder'
'setVmTipGroup'
'setVmName'
'swapSnapshot4disk'
'swapDisk4disk'
'setVmMerge'
'cloneVMs'
'setVmSize'
'setVmZone'
'setDiskSku'
'setDiskSize'
'setDiskMaxShares'
'setDiskTier'
'setDiskBursting'
'setDiskIOps'
'setDiskMBps'
'setDiskCaching'
'setAcceleratedNetworking'
'setPrivateIpAlloc'
'removeFQDN'
'createProximityPlacementGroup'
'createAvailabilitySet'
'setGroupTipSession'
'setVmFaultDomain'
'createVmssFlex'
'attachVmssFlex'
'attachAvailabilitySet'
'attachProximityPlacementGroup'
)
$workflowParameters = @(
'cloneMode'
'updateMode'
'archiveMode'
'mergeMode'
'patchMode'
'skipArmTemplate'
'skipSnapshots'
'stopVMsSourceRG'
'skipBackups'
'skipRemoteCopy'
'skipDeployment'
'skipDeploymentVMs'
'skipRestore'
'stopRestore'
'continueRestore'
'skipExtensions'
'startWorkload'
'stopVMsTargetRG'
'deleteSnapshots'
'deleteSourceSA'
'simulate'
'restartRemoteCopy'
'justCopyBlobs'
'justCopySnapshots'
'justCopyDisks'
'justStopCopyBlobs'
'justCreateSnapshots'
'justDeleteSnapshots'
'skipStartSAP'
)
$program = 'RGCOPY'
$suppliedModes = @()
$cloneOrMergeMode = $False
# Clone Mode
if ($cloneMode) {
$suppliedModes += 'cloneMode'
$rgcopyMode = 'Clone Mode'
$cloneOrMergeMode = $True
$useBicep = $True
}
# Merge Mode
if ($mergeMode) {
$suppliedModes += 'mergeMode'
$rgcopyMode = 'Merge Mode'
$cloneOrMergeMode = $True
$useBicep = $True
}
# Patch Mode
if ($patchMode) {
$suppliedModes += 'patchMode'
$rgcopyMode = 'Patch Mode'
$useBicep = $True
}
# Update Mode
if ($updateMode) {
$suppliedModes += 'updateMode'
$rgcopyMode = 'Update Mode'
}
# Archive Mode
if ($archiveMode) {
$suppliedModes += 'archiveMode'
$rgcopyMode = 'Archive Mode'
}
# Copy Mode
if ($suppliedModes.count -eq 0) {
$rgcopyMode = 'Copy Mode'
$copyMode = $True
}
# process only sourceRG ?
if ( $updateMode `
-or $patchMode `
-or $cloneMode `
-or $justCreateSnapshots `
-or $justDeleteSnapshots `
-or ($mergeMode -and ('targetRG' -notin $boundParameterNames)) `
) {
$SourceOnlyMode = $True
$targetRG = $sourceRG
}
else {
$SourceOnlyMode = $False
}
# constants
$snapshotExtension = 'rgcopy'
$netAppSnapshotName = 'rgcopy'
$targetSaContainer = 'rgcopy'
$sourceSaShare = 'rgcopy'
$netAppPoolSizeMinimum = 4 * 1024 * 1024 * 1024 * 1024
# azure tags
$azTagMonitorRule = 'rgcopy.MonitorRule'
$azTagVmType = 'rgcopy.VmType'
$azTagTipGroup = 'rgcopy.TipGroup'
$azTagDeploymentOrder = 'rgcopy.DeploymentOrder'
$azTagSapMonitor = 'rgcopy.Extension.SapMonitor'
$azTagDiagSettingsSA = 'rgcopy.diagSettingsSA'
$azTagDiagSettingsContainer = 'rgcopy.diagSettingsContainer'
$azTagScriptStartSap = 'rgcopy.ScriptStartSap'
$azTagScriptStartLoad = 'rgcopy.ScriptStartLoad'
$azTagScriptStartAnalysis = 'rgcopy.ScriptStartAnalysis'
$azTagSmbLike = 'rgcopy.smb.*'
$azTagSub = 'rgcopy.smb.Subscription'
$azTagRG = 'rgcopy.smb.ResourceGroup'
$azTagSA = 'rgcopy.smb.StorageAccount'
$azTagPath = 'rgcopy.smb.Path'
$azTagLun = 'rgcopy.smb.DiskLun'
$azTagVM = 'rgcopy.smb.VM'
if (!$IsWindows -and ('hostPlainText' -notin $boundParameterNames)) {
$hostPlainText = $True
}
#--------------------------------------------------------------
function test-match {
#--------------------------------------------------------------
param (
$name,
$value,
$match,
$partName,
$syntax
)
if ($value -cnotmatch $match) {
if ($Null -eq $syntax) {
write-logFileError "Invalid parameter '$name'" `
"Value is '$value'" `
"Value must match '$match'"
}
else {
write-logFileError "Invalid parameter '$name'" `
"The syntax is: '$syntax'" `
"Value of '$partName' is '$parameterValue'" `
"Value must match '$match'"
}
}
}
#--------------------------------------------------------------
function test-names {
#--------------------------------------------------------------
# netAppPoolGB
if (($netAppPoolGB * 1024 * 1024 * 1024) -lt $netAppPoolSizeMinimum) {
write-logFileError "Invalid parameter 'netAppPoolGB'" `
"Value must be at least 4096"
}
test-values 'netAppServiceLevel' $netAppServiceLevel @('Standard', 'Premium', 'Ultra')
test-values 'createDisksTier' $createDisksTier @('P2', 'P3', 'P4', 'P6', 'P10', 'P15', 'P20', 'P30', 'P40', 'P50')
#--------------------------------------------------------------
# resource groups
# Can include alphanumeric, underscore, parentheses, hyphen, period (except at end)
# length: 1-90
$match = '^[a-zA-Z0-9_\-\(\)\.]{0,89}[a-zA-Z0-9_\-\(\)]$'
test-match 'targetRG' $script:targetRG $match
test-match 'sourceRG' $script:sourceRG $match
if ($script:blobsRG.Length -ne 0) {
test-match 'blobsRG' $script:blobsRG $match
}
#--------------------------------------------------------------
# storage accounts
# Lowercase letters and numbers
# length: 3-24
$match = '^[a-z0-9]{3,24}$'
# targetSA
if ($script:targetSA.Length -eq 0) {
$name = ($script:targetRG -replace '[_\.\-\(\)]', '').ToLower()
# truncate name
$len = (24, $name.Length | Measure-Object -Minimum).Minimum
$name = $name.SubString(0,$len)
# name too short
if ($len -lt 3) {
$name = 'blob' + $name
}
$script:targetSA = $name
}
else {
test-match 'targetSA' $script:targetSA $match
}
# sourceSA
if ($script:sourceSA.Length -eq 0) {
$name = ($script:sourceRG -replace '[_\.\-\(\)]', '').ToLower()
# truncate name
$len = (21, $name.Length | Measure-Object -Minimum).Minimum
$script:sourceSA = 'nfs' + $name.SubString(0,$len)
}
else {
test-match 'sourceSA' $script:sourceSA $match
}
# blobsSA
if ($script:blobsSA.Length -ne 0) {
test-match 'blobsSA' $script:blobsSA $match
}
#--------------------------------------------------------------
# netAppAccountName
# The name must begin with a letter and can contain letters, numbers, underscore ('_') and hyphens ('-') only.
# The name must be between 1 and 128 characters.
$match = '^[a-zA-Z][_\-a-zA-Z0-9]{0,127}$'
if ($script:netAppAccountName.length -eq 0) {
$script:netAppAccountName = 'rgcopy' + '-' + ($targetRG -replace '[\.\(\)]', '')
}
else {
test-match 'netAppAccountName' $script:netAppAccountName $match
}
#--------------------------------------------------------------
# netAppPoolName
# The name must begin with a letter and can contain letters, numbers, underscore ('_') and hyphens ('-') only.
# The name must be between 1 and 128 characters.
$match = '^[a-zA-Z][_\-a-zA-Z0-9]{0,127}$'
if ($script:netAppPoolName.length -eq 0) {
$script:netAppPoolName = "rgcopy-$($netAppServiceLevel.ToLower()[0])-pool"
}
else {
test-match 'netAppPoolName' $script:netAppPoolName $match
}
#--------------------------------------------------------------
# archiveContainer
# This name may only contain lowercase letters, numbers, and hyphens, and must begin with a letter or a number.
# Each hyphen must be preceded and followed by a non-hyphen character.
# The name must also be between 3 and 63 characters long.
$match = '^[a-z0-9][a-z0-9\-]{1,61}[a-z0-9]$'
if ($script:archiveContainer.length -eq 0) {
$name = ($sourceRG `
-replace '[_\.\(\)]', '-' `
-replace '\-+', '-' `
-replace '^\-+', '' `
-replace '\-+$', '' `
).ToLower()
# truncate name
$len = (63, $name.Length | Measure-Object -Minimum).Minimum
$name = $name.SubString(0,$len)
# hyphen could be last character after truncation
$name = $name -replace '\-+$', ''
# name too short
if ($name.length -lt 3) {
$name += '-dir'
}
$script:archiveContainer = $name
}
else {
test-match 'archiveContainer' $script:archiveContainer $match
$test = $script:archiveContainer -replace '\-+', '-'
if ($test -ne $script:archiveContainer) {
write-logFileError "Invalid parameter 'archiveContainer'" `
"Value is '$script:archiveContainer'" `
"Each hyphen must be preceded and followed by a non-hyphen character"
}
}
}
#--------------------------------------------------------------
function test-values {
#--------------------------------------------------------------
param (
$parameterName,
$parameterValue,
$allowedValues,
$partName,
$syntax
)
$list = '{'
$sep = ''
foreach ($item in $allowedValues) {
$list += "$sep $item"
$sep = ','
}
$list += ' }'
if ($parameterValue -notin $allowedValues) {
if ($Null -ne $syntax) {
write-logFileError "Invalid parameter '$parameterName'" `
"The syntax is: '$syntax'" `
"Value of '$partName' is '$parameterValue'" `
"Allowed values are: $list"
}
elseif ($Null -ne $partName) {
write-logFileError "Invalid parameter '$parameterName'" `
"Value of $partName is '$parameterValue'" `
"Allowed values are: $list"
}
else {
write-logFileError "Invalid parameter '$parameterName'" `
"Value is '$parameterValue'" `
"Allowed values are: $list"
}
}
}
#--------------------------------------------------------------
function test-subnet {
#--------------------------------------------------------------
param (
$parameterName,
$parameterValue,
$defaultSubnet
)
$param = $parameterValue -replace '\s+', ''
# check for parameter parts
$addressPrefix, $vnetName = $param -split '@'
if (($addressPrefix.count -ne 1) -or ($vnetName.count -ne 1)) {
write-logFileError "Invalid parameter '$parameterName'" `
"Parameter must match <addressPrefix>@<vnet>"
}
# check prefix
if ($addressPrefix -notmatch '\d+\.\d+\.\d+\.\d+/\d+') {
write-logFileError "Invalid parameter '$parameterName'" `
"Invalid addressPrefix '$addressPrefix'" `
"AddressPrefix must match '\d+\.\d+\.\d+\.\d+/\d+'"
}
# Get source VNETs
$script:sourceVNETs = @( Get-AzVirtualNetwork `
-ResourceGroupName $sourceRG `
-ErrorAction 'SilentlyContinue' )
test-cmdlet 'Get-AzVirtualNetwork' "Could not get VNETs of resource group $sourceRG"
$vnet = $script:sourceVNETs | Where-Object Name -eq $vnetName
if ($Null -eq $vnet) {
write-logFileError "Invalid parameter '$parameterName'" `
"Vnet '$vnet' not found"
}
$subnetNames = $vnet.Subnets.Name
$subnetName = $defaultSubnet
$i = 1
while ($subnetName -in $subnetNames) {
$i++
$subnetName = "$defaultSubnet$i"
}
return $vnetName, $subnetName, $addressPrefix
}
#--------------------------------------------------------------
function test-cmdlet {
#--------------------------------------------------------------
param (
$azFunction,
$errorText,
$errorText2,
[switch] $always
)
if (!$? -or $always -or $script:errorOccured) {
write-logFileError $errorText `
"$azFunction failed" `
$errorText2 `
-lastError
}
}
#--------------------------------------------------------------
function write-logFile {
#--------------------------------------------------------------
param (
$print,
$ForegroundColor,
[switch] $NoNewLine,
[switch] $blinking
)
$print = write-secureString $print
if ($Null -eq $print) {
$print = ' '
}
if ($blinking) {
$print = "`e[5m" + $print + "`e[0m"
}
[string] $script:LogFileLine += $print
$par = @{ Object = $print }
if ($NoNewLine) {
$par.Add('NoNewLine', $True)
}
if ($Null -ne $ForegroundColor) {
$par.Add('ForegroundColor', $ForegroundColor)
}
# write to host
if ($hostPlainText) {
if (!$NoNewLine) {
Write-Host $script:LogFileLine
}
}
else {
Write-Host @par
}
# write to log file
if (!$NoNewLine) {
try {
$script:LogFileLine | Out-File $logPath -Append
}
catch {
Start-Sleep 1
# one retry (if file is opened by virus scanner)
$script:LogFileLine | Out-File $logPath -Append
}
[string] $script:LogFileLine = ''
}
}
#--------------------------------------------------------------
function write-LogFilePipe {
#--------------------------------------------------------------
[CmdletBinding()]
Param (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
$InputObject,
[switch] $errorLog
)
begin {
$log = @()
}
process {
$log += $InputObject
}
end {
$log | Out-Host
if ($PsStyle.OutputRendering -eq 'Ansi') {
$PsStyle.OutputRendering = 'PlainText'
$log | Out-File $logPath -Append
$PsStyle.OutputRendering = 'Ansi'
}
else {
$log | Out-File $logPath -Append
}
}
}
#--------------------------------------------------------------
function write-logFileWarning {
#--------------------------------------------------------------
param (
$myWarning,
$param2,
$param3,
$param4,
$stopCondition,
[switch] $stopWhenForceVmChecks,
[switch] $noSkip
)
# write error
if (($stopWhenForceVmChecks -and $forceVmChecks) `
-or ($stopCondition -eq $True)) {
if ($simulate) {
write-logFile "WARNING: $myWarning" -ForegroundColor 'red'
}
else {
write-logFileError $myWarning $param2 $param3 $param4
}
}
# write warning
else {
write-logFile "WARNING: $myWarning" -ForegroundColor 'yellow'
}
if ($param2.length -ne 0) { write-logFile $param2 }
if ($param3.length -ne 0) { write-logFile $param3 }
if ($param4.length -ne 0) { write-logFile $param4 }
# new line
if (($param2.length -ne 0) -and !$noSkip) { write-logFile }
}
#--------------------------------------------------------------
function write-logFileConfirm {
#--------------------------------------------------------------
param (
$text
)
write-logFile ('-' * $starCount) -ForegroundColor 'Red'
write-logFile $text -ForegroundColor 'red'
write-logFile ('-' * $starCount) -ForegroundColor 'Red'
write-logFile
if ($simulate) {
write-logFile "Enter 'yes' to continue"
write-logFile "answer not needed in simulation mode"
write-logFile
}
else {
$answer = Read-Host "Enter 'yes' to continue"
write-logFile
if ($answer -ne 'yes') {
write-logFile "The answer was '$answer'"
write-logFile
write-zipFile 0
}
}
}
#--------------------------------------------------------------
function write-zipFile {
#--------------------------------------------------------------