-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreate_Team.ps1
9156 lines (7854 loc) · 293 KB
/
Create_Team.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
<#
Create_Team.ps1: Create a Team site and associated elements for the SAPonAzure Strategic Partnership Team
version: 0.1
version date: January 2022
Author: Troy Shane
Public Github:
Microsoft intern:
//
// 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.1
#Requires -Modules ''
param (
#--------------------------------------------------------------
# essential parameters
#--------------------------------------------------------------
# subscriptions and User
,[string] $targetSub # Target Subscription display name
,[string] $targetSubUser # User Name
,[string] $targetSubTenant # Tenant Name (optional)
# operation switches
,[switch] $skipArmTemplate # skip ARM template creation
,[switch] $skipSnapshots # skip snapshot creation of disks and volumes (in sourceRG)
,[switch] $skipBackups # skip backup of files (in sourceRG)
,[switch] $skipBlobs # skip BLOB creation (in targetRG)
,[switch] $skipDeployment # skip deployment (in targetRG)
,[switch] $skipDeploymentVMs # skip part step: deploy Virtual Machines
,[switch] $skipRestore # skip part step: restore files
,[switch] $skipDeploymentAms # skip part step: deploy AMS
,[switch] $skipExtensions # skip part step: install VM extensions
,[switch] $startWorkload # start workload (script $scriptStartLoadPath on VM $scriptVm)
,[switch] $stopRestore # run all steps until (excluding) Restore
,[switch] $continueRestore # run Restore and all later steps
,[switch] $stopVMs # stop VMs after deployment
#--------------------------------------------------------------
# file locations
#--------------------------------------------------------------
,[string] $pathArmTemplate # given ARM template file
,[string] $pathArmTemplateAms # given ARM template file for AMS deployment
,[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
#--------------------------------------------------------------
# AMS and script parameter
#--------------------------------------------------------------
# AMS (Azure Monitoring for SAP) parameters
,[string] $amsInstanceName # Name of AMS instance to be created in the target RG
,[string] $amsWsName # Name of existing Log Analytics workspace for AMS
,[string] $amsWsRG # Resource Group of existing Log Analytics workspace for AMS
,[switch] $amsWsKeep # Keep existing Log Analytics workspace of sourceRG
,[switch] $amsShareAnalytics # Sharing Customer Analytics Data with Microsoft
,[SecureString] $dbPassword # = (ConvertTo-SecureString -String 'secure-password' -AsPlainText -Force)
,[boolean] $amsUsePowerShell = $True # use PowerShell cmdlets rather than ARM template for AMS deployment
# script location of shell scripts inside the VM
,[string] $scriptVm # if not set, then calculated from vm tag rgcopy.ScriptStartSap
,[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
# VM extensions
,$installExtensionsSapMonitor = @() # Array of VMs where SAP extension should be installed
,$installExtensionsAzureMonitor = @() # Array of VMs where VM extension should be installed
#--------------------------------------------------------------
# default values
#--------------------------------------------------------------
,[string] $setOwner = '*' # Owner-Tag of Resource Group; default: $targetSubUser
,[switch] $ignoreTags # ignore rgcopy*-tags for target RG CONFIGURATION
,[switch] $verboseLog # detailed output for backup/restore files
#--------------------------------------------------------------
# resource configuration parameters
#--------------------------------------------------------------
<# 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
#>
,$setTeamName = @()
# renames VM resource name (not name on OS level)
# usage: $setVmName = @("$vmNameNew@$vmNameOld", ...)
# set VM name dbserver for VM hana (=rename hana) @("dbserver@hana")
,$setTeamMembers = @()
# renames VM resource name (not name on OS level)
# usage: $setVmName = @("$vmNameNew@$vmNameOld", ...)
# set VM name dbserver for VM hana (=rename hana) @("dbserver@hana")
#,$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")
#--------------------------------------------------------------
# parameters for cleaning an incomplete CreateTeam run
#--------------------------------------------------------------
,[switch] $restartCreateTeam # restart a failed CreateTeam
#--------------------------------------------------------------
# experimental parameters: DO NOT USE!
#--------------------------------------------------------------
,$generalizedUser = @()
,$generalizedPasswd = @() # will be checked below for data type [SecureString] or [SecureString[]]
)
$ErrorActionPreference = 'Stop'
# constants
$snapshotExtension = 'rgcopy'
$netAppSnapshotName = 'rgcopy'
$targetSaContainer = 'rgcopy'
$sourceSaShare = 'rgcopy'
$targetNetAppPool = 'rgcopy'
# azure tags
$azTagTipGroup = 'rgcopy.TipGroup'
$azTagDeploymentOrder = 'rgcopy.DeploymentOrder'
$azTagSapMonitor = 'rgcopy.Extension.SapMonitor'
$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'
# Storage Account in targetRG (between 3 and 24 characters)
if ($targetSA.Length -eq 0) {
$targetSA = ($targetRG -replace '[_\.\-\(\)]', '').ToLower()
$len = (24, $targetSA.Length | Measure-Object -Minimum).Minimum
if ($len -lt 3) { $targetSA += 'blob'; $len += 4}
$targetSA = $targetSA.SubString(0,$len)
}
# Storage Account in sourceRG
if ($sourceSA.Length -eq 0) {
$sourceSA = ($sourceRG -replace '[_\.\-\(\)]', '').ToLower()
$len = (21, $sourceSA.Length | Measure-Object -Minimum).Minimum
$sourceSA = 'smb' + $sourceSA.SubString(0,$len)
}
# Azure NetApp Files Account
#$targetAnfAccount = $targetSA
# AMS Name (between 6 and 30 characters)
if ($amsInstanceName.Length -eq 0) { $amsInstanceName = $targetSA }
# Storage Account for disk creation
if ($blobsRG.Length -eq 0) { $blobsRG = $targetRG }
if ($blobsSA.Length -eq 0) { $blobsSA = $targetSA }
if ($blobsSaContainer.Length -eq 0) { $blobsSaContainer = $targetSaContainer }
if ($skipBlobs -ne $True) {
$blobsRG = $targetRG
$blobsSA = $targetSA
$blobsSaContainer = $targetSaContainer
}
# file names and location
if ($(Test-Path $pathExportFolder) -eq $False) {
$pathExportFolderNotFound = $pathExportFolder
$pathExportFolder = '~'
}
$pathExportFolder = Resolve-Path $pathExportFolder
# default file paths
$importPath = Join-Path -Path $pathExportFolder -ChildPath "rgcopy.$sourceRG.SOURCE.json"
$exportPath = Join-Path -Path $pathExportFolder -ChildPath "rgcopy.$targetRG.TARGET.json"
$exportPathAms = Join-Path -Path $pathExportFolder -ChildPath "rgcopy.$targetRG.AMS.json"
$logPath = Join-Path -Path $pathExportFolder -ChildPath "rgcopy.$targetRG.TARGET.log"
$timestampSuffix = (Get-Date -Format 'yyyy-MM-dd__HH-mm-ss')
# fixed file paths
$tempPathText = Join-Path -Path $pathExportFolder -ChildPath "rgcopy.$targetRG.TEMP.txt"
$tempPathJson = Join-Path -Path $pathExportFolder -ChildPath "rgcopy.$targetRG.TEMP.json"
$zipPath = Join-Path -Path $pathExportFolder -ChildPath "rgcopy.$targetRG.$timestampSuffix.zip"
$savedRgcopyPath = Join-Path -Path $pathExportFolder -ChildPath "rgcopy.txt"
#--------------------------------------------------------------
function write-logFile {
#--------------------------------------------------------------
param ( [Parameter(Position=0)] $print,
[switch] $NoNewLine,
$ForegroundColor )
if ($Null -eq $print) { $print = ' ' }
[string] $script:LogFileLine += $print
$par = @{ Object = $print }
if ($NoNewLine) { $par.Add('NoNewLine', $True) }
if ($Null -ne $ForegroundColor) { $par.Add('ForegroundColor', $ForegroundColor) }
Write-Host @par
if (!$NoNewLine) {
Write-Host $script:LogFileLine *>>$logPath
[string] $script:LogFileLine = ''
}
}
#--------------------------------------------------------------
function write-logFileWarning {
#--------------------------------------------------------------
param ( $myWarning )
write-logFile "WARNING: $myWarning" -ForegroundColor 'yellow'
}
#--------------------------------------------------------------
function write-zipFile {
#--------------------------------------------------------------
param ( $exitCode)
write-logFile -ForegroundColor 'Cyan' "All files saved in zip file: $zipPath"
write-logFile "RGCOPY EXIT CODE: $exitCode"
write-logFile
[array] $files = @($logPath)
if ($skipArmTemplate -ne $True) {
if ($(Test-Path -Path $importPath) -eq $True) {$files += $importPath}
}
if ($(Test-Path -Path $savedRgcopyPath) -eq $True) {$files += $savedRgcopyPath}
if ($(Test-Path -Path $exportPath) -eq $True) {$files += $exportPath}
if ($(Test-Path -Path $exportPathAms) -eq $True) {$files += $exportPathAms}
$parameter = @{ LiteralPath = $files
DestinationPath = $zipPath }
Compress-Archive @parameter
[console]::ResetColor()
$ErrorActionPreference = 'Stop'
exit $exitCode
}
#--------------------------------------------------------------
function write-logFileError {
#--------------------------------------------------------------
param ( $param1,
$param2,
$param3,
$lastError)
if ($lastError.length -ne 0) {
write-logFile
write-logFile $lastError -ForegroundColor 'yellow'
}
write-logFile
write-logFile ('=' * 60) -ForegroundColor 'red'
write-logFile $param1 -ForegroundColor 'yellow'
if ($param2.length -ne 0) {
write-logFile $param2 -ForegroundColor 'yellow'
}
if ($param3.length -ne 0) {
write-logFile $param3 -ForegroundColor 'yellow'
}
write-logFile ('=' * 60) -ForegroundColor 'red'
write-logFile
$stack = Get-PSCallStack
write-logFile "RGCOPY TERMINATED: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss \U\T\Cz')" -ForegroundColor 'red'
write-logFile "CALL STACK: $($stack[-2].ScriptLineNumber) $($stack[-2].Command)"
for ($i = $stack.count-3; $i -ge 2; $i--) {
write-logFile " $($stack[$i].ScriptLineNumber) $($stack[$i].Command)"
}
write-logFile "ERROR LINE: $($stack[1].ScriptLineNumber) $($stack[1].Command)"
write-logFile "ERROR MESSAGE: $param1"
write-zipFile 1
}
#--------------------------------------------------------------
function write-logFileUpdates {
#--------------------------------------------------------------
param ( [Parameter(Position=0)] [string] $resourceType,
[Parameter(Position=1)] [string] $resource,
[Parameter(Position=2)] [string] $action,
[Parameter(Position=3)] [string] $value,
[Parameter(Position=4)] [string] $comment1,
[Parameter(Position=5)] [string] $comment2)
if ($action -like 'delete*') {$colorAction = 'Blue'}
elseif ($action -like 'keep*') {$colorAction = 'DarkGray'}
else {$colorAction = 'Green'}
if ($resource -like '<*') {$colorResource = 'Cyan'}
else {$colorREsource = 'Gray'}
if (($value.length -ne 0) -and ($comment1.length -eq 0) -and ($value -notin @('True','False'))) {$value = "'$value'"}
$spaces = ''
$numSpace = 40 - $resourceType.length - $resource.length
if ($numSpace -gt 0) {$spaces = ' '*$numSpace}
Write-logFile "$resourceType " -NoNewline -ForegroundColor 'DarkGray'
write-logFile "$resource $spaces" -NoNewline -ForegroundColor $colorResource
Write-logFile "$action " -NoNewline -ForegroundColor $colorAction
Write-logFile $value -NoNewline
Write-logFile $comment1 -NoNewline -ForegroundColor 'Cyan'
Write-logFile $comment2
}
#--------------------------------------------------------------
function write-logFileTab {
#--------------------------------------------------------------
param ( [Parameter(Position=0)] [string] $resourceType,
[Parameter(Position=1)] [string] $resource,
[Parameter(Position=2)] [string] $info,
[switch] $noColor)
if ($noColor) {$resourceColor = 'Gray'}
else {$resourceColor = 'Green'}
Write-logFile " $(($resourceType + (' '*20)).Substring(0,20))" -NoNewline
write-logFile "$resource " -NoNewline -ForegroundColor $resourceColor
Write-logFile "$info"
}
#--------------------------------------------------------------
function protect-secureString {
#--------------------------------------------------------------
param ( $key, $value)
if (($value -is [securestring]) -or ($key -like '*passw*') -or ($key -like '*credential*')) {
return '*****'
}
return $value
}
#--------------------------------------------------------------
function write-hashTableOutput {
#--------------------------------------------------------------
param ( $key, $value)
$protectedValue = protect-secureString $key $value
$script:hashTableOutput += New-Object psobject -Property @{
Parameter = $key
Value = $protectedValue
}
}
#--------------------------------------------------------------
function write-logFileHashTable {
#--------------------------------------------------------------
param ( $paramHashTable)
$script:hashTableOutput = @()
$paramHashTable.GetEnumerator()
| ForEach-Object {
$paramKey = $_.Key
$paramValue = $_.Value
# array
if ($paramValue -is [array]) {
for ($i = 0; $i -lt $paramValue.Count; $i++) {
# simple array (or array of array)
if ($paramValue[$i] -isnot [hashtable]) {
write-hashTableOutput "$paramKey[$i]" $paramValue[$i]
}
}
}
# hashtable
elseif ($paramValue -is [hashtable]) {
foreach ($item in $paramValue.GetEnumerator()) {
# simple hashtable (or hashtable of array)
if ($item.Value -isnot [hashtable]) {
write-hashTableOutput "$paramKey[$($item.Key)]" $item.Value
}
# hashtable of hashtable
else {
foreach ($subitem in $item.Value.GetEnumerator()) {
if ($subitem.Value -isnot [hashtable]) {
write-hashTableOutput "$paramKey[$($item.Key)][$($subitem.Key)]" $subitem.Value
}
}
}
}
}
# scalar
else {
write-hashTableOutput $paramKey $paramValue
}
}
$script:hashTableOutput
| Select-Object Parameter, Value
| Sort-Object Parameter
| Format-Table
| Tee-Object -FilePath $logPath -append
| Out-Host
}
#--------------------------------------------------------------
function write-actionStart {
#--------------------------------------------------------------
param ( $text, $maxDegree)
if ($null -ne $maxDegree) {
if ($maxDegree -gt 1) {
$text = $text + " (max degree of parallelism: $maxDegree)"
}
}
write-logFile ('*' * 63) -ForegroundColor DarkGray
write-logFile $text
write-logFile ('>>>' + ('-' * 60)) -ForegroundColor DarkGray
write-logFile (Get-Date -Format 'yyyy-MM-dd HH:mm:ss \U\T\Cz')
write-logFile
}
#--------------------------------------------------------------
function write-actionEnd {
#--------------------------------------------------------------
write-logFile
write-logFile ('<<<' + ('-' * 60)) -ForegroundColor DarkGray
write-logFile
write-logFile
}
#--------------------------------------------------------------
function get-ParameterConfiguration {
#--------------------------------------------------------------
param ( $config)
# split configuration
$script:paramConfig1,$script:paramConfig2,$script:paramConfig3,$script:paramConfig4 = $config -split '/'
# a maximum of 4 configuration parts:
if ($script:paramConfig4.count -gt 1) {
write-logFileError "Invalid parameter '$script:paramName'" `
"Configuration: '$config'" `
"The configuration contains more than three '/'"
}
if ($script:paramConfig1.length -eq 0) { $script:paramConfig1 = $Null }
if ($script:paramConfig2.length -eq 0) { $script:paramConfig2 = $Null }
if ($script:paramConfig3.length -eq 0) { $script:paramConfig3 = $Null }
if ($script:paramConfig4.length -eq 0) { $script:paramConfig4 = $Null }
# part 1 or part 2 must exist
if (($Null -eq $script:paramConfig1) -and ($Null -eq $script:paramConfig2)) {
write-logFileError "Invalid parameter '$script:paramName'" `
"Configuration: '$config'" `
"Ivalid configuration"
}
}
#--------------------------------------------------------------
function get-ParameterRule {
#--------------------------------------------------------------
# a parameter is an array of rules
# each rule has the form: configuration@resources
# each configuration consists of many parts separated by slash (/)
# resources are separated by comma (,)
$script:paramConfig = $Null
$script:paramConfig1 = $Null
$script:paramConfig2 = $Null
$script:paramConfig3 = $Null
$script:paramConfig4 = $Null
[array] $script:paramResources = @()
[array] $script:paramVMs = @()
[array] $script:paramDisks = @()
# no rule exists or last rule reached
if ($script:paramRules.count -le $script:paramIndex) { return }
# get current rule
$currentRule = $script:paramRules[$script:paramIndex++]
# check data type of rule
if ($currentRule -isnot [string]) {
write-logFileError "Invalid parameter '$script:paramName'" `
'Invalid data type, the rule is not a string'
}
# remove white spaces
$currentRule = $currentRule -replace '\s+', ''
# check for quotes
if (($currentRule -like '*"*') -or ($currentRule -like "*'*")) {
write-logFileError "Invalid parameter '$script:paramName'" `
"Rule: '$currentRule'" `
'Quotes not allowed as part of a name'
}
# split rule
$script:paramConfig, $resources = $currentRule -split '@'
# there must be 1 configuration
# and 0 or 1 comma separated list of resources ( not more than one @ allowed per rule)
if ($script:paramConfig.length -eq 0) {
write-logFileError "Invalid parameter '$script:paramName'" `
"Rule: '$currentRule'" `
'The rule does not contain a configuration'
}
if ($resources.count -gt 1) {
write-logFileError "Invalid parameter '$script:paramName'" `
"Rule: '$currentRule'" `
"The rule contains more than one '@'"
}
if ($currentRule -like '*@') {
write-logFileError "Invalid parameter '$script:paramName'" `
"Rule: '$currentRule'" `
"The rule contains no resource after the '@'"
}
# split configuration
get-ParameterConfiguration $script:paramConfig
# split resources
if ($resources.length -eq 0) { [array] $script:paramResources = @() }
else { [array] $script:paramResources = $resources -split ',' }
# remove empty resources (double commas)
[array] $script:paramResources = $script:paramResources | Where-Object {$_.length -ne 0}
# get resource types: VMs and disks
if ($script:paramResources.count -eq 0) {
[array] $script:paramVMs = $script:copyVMs.keys
[array] $script:paramDisks = $script:copyDisks.keys
}
else {
[array] $script:paramVMs = $script:copyVMs.keys | Where-Object {$_ -in $script:paramResources}
[array] $script:paramDisks = $script:copyDisks.keys | Where-Object {$_ -in $script:paramResources}
# check existence
if ($script:paramName -like 'setVm*') {
[array] $notFound = $script:paramResources | Where-Object {$_ -notin $script:paramVMs}
if ($notFound.count -ne 0) {
write-logFileError "Invalid parameter '$script:paramName'" `
"Rule: '$currentRule'" `
"VM '$($notFound[0])' not found"
}
}
if ($script:paramName -like 'setDisk*') {
[array] $notFound = $script:paramResources | Where-Object {$_ -notin $script:paramDisks}
if ($notFound.count -ne 0) {
write-logFileError "Invalid parameter '$script:paramName'" `
"Rule: '$currentRule'" `
"Disk '$($notFound[0])' not found"
}
}
}
}
#--------------------------------------------------------------
function set-parameter {
#--------------------------------------------------------------
# a parameter is an array of rules
# each rule has the form: configuration@resources
# each configuration consists of many parts separated by slash (/)
# resources are separated by comma (,)
param ( $parameterName, $parameter, $type, $type2)
$script:paramName = $parameterName
if (($parameter -isnot [array]) -and ($parameter -isnot [string])) {
write-logFileError "Invalid parameter '$script:paramName'" `
"invalid data type"
}
# paramRules as array
if ($parameter.count -eq 0) { [array] $script:paramRules = @() }
else { [array] $script:paramRules = $parameter }
# set script variable for index of rules (current rule)
[int] $script:paramIndex = 0
$script:paramValues = @{}
if ($script:paramRules.count -gt 1) {
# process first rule last -> first rule wins
[array]::Reverse($script:paramRules)
# process global rules (no @) first
[array] $head = $script:paramRules | Where-Object {$_ -notlike '*@*'}
[array] $tail = $script:paramRules | Where-Object {$_ -like '*@*'}
[array] $script:paramRules = $head + $tail
}
#--------------------------------------------------------------
# get all resource names from ARM template
if ($Null -ne $type) {
[array] $resourceNames = ($script:resourcesALL | Where-Object type -eq $type).name
}
else {
return # no ARM resource types supplied
}
if ($Null -ne $type2) {
[array] $resourceNames += ($script:resourcesALL | Where-Object type -eq $type2).name
}
get-ParameterRule
while ($Null -ne $script:paramConfig) {
if ($script:paramResources.count -eq 0) {
[array] $myResources = $resourceNames
}
else {
[array] $myResources = $script:paramResources
# check existence
[array] $notFound = $script:paramResources | Where-Object {$_ -notin $resourceNames}
if ($notFound.count -ne 0) {
write-logFileError "Invalid parameter '$script:paramName'" `
"Resource '$($notFound[0])' not found"
}
}
foreach ($res in $myResources) {
$script:paramValues[$res] = $script:paramConfig
}
get-ParameterRule
}
}
#--------------------------------------------------------------
function get-scriptBlockParam {
#--------------------------------------------------------------
param ( $scriptParameter, $scriptBlock, $myMaxDOP)
if ($myMaxDOP -eq 1) {
return @{ Process = $scriptBlock }
}
else {
$scriptReturn = [Scriptblock]::Create($scriptParameter + $scriptBlock.toString())
return @{ ThrottleLimit = $myMaxDOP; Parallel = $scriptReturn }
}
}
#--------------------------------------------------------------
function compare-resources{
#--------------------------------------------------------------
param ( $res1, $res2)
return (($res1 -replace '\s+', '') -eq ($res2 -replace '\s+', ''))
}
#--------------------------------------------------------------
function get-resourceString {
#--------------------------------------------------------------
# assembles string for Azure Resource ID
param ( $subscriptionID, $resourceGroup,
$resourceArea,
$mainResourceType, $mainResourceName,
$subResourceType, $subResourceName)
$resID = "/subscriptions/$subscriptionID/resourceGroups/$resourceGroup/providers/$resourceArea/$mainResourceType/$mainResourceName"
if ($Null -ne $subResourceType) { $resID += "/$subResourceType/$subResourceName" }
return $resID
}
#--------------------------------------------------------------
function get-resourceFunction {
#--------------------------------------------------------------
# assembles string for Azure Resource ID using function resourceId()
param ( $resourceArea,
$mainResourceType, $mainResourceName,
$subResourceType, $subResourceName)
$resFunction = "[resourceId('$resourceArea/$mainResourceType"
if ($Null -ne $subResourceType) {
$resFunction += "/$subResourceType"
}
# check for functions, e.g. parameters()
if ($mainResourceName -like '*(*') {$ap = ''} else {$ap = "'"}
$resFunction += "', $ap$mainResourceName$ap"
if ($Null -ne $subResourceType) {
# check for functions, e.g. parameters()
if ($subResourceName -like '*(*') {$ap = ''} else {$ap = "'"}
$resFunction += ", $ap$subResourceName$ap"
}
$resFunction += ")]"
return $resFunction
}
#--------------------------------------------------------------
function get-functionBody {
#--------------------------------------------------------------
param ( $str, $inputString)
$from = $str.IndexOf('(')
if ($from -eq -1) {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
$to = $str.LastIndexOf(')')
if ($to -ne ($str.length -1)) {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
$function = $str.Substring(0, $from)
$body = $str.Substring( $from + 1, $to - $from - 1)
return $function, $body
}
#--------------------------------------------------------------
function remove-dependencies {
#--------------------------------------------------------------
param ( $dependsOn,
$remove,
$keep)
if ($keep.length -ne 0) {
[array] $return = $dependsOn | Where-Object { $_ -like "*'$keep'*" }
}
elseif ($remove.length -ne 0) {
[array] $return = $dependsOn | Where-Object { $_ -notlike "*'$remove'*" }
}
if ($return.count -eq 0) {
$return = @()
}
return $return
}
#--------------------------------------------------------------
function remove-resources {
#--------------------------------------------------------------
param ( $type,
$names)
if ('names' -notin $PSBoundParameters.Keys) {
[array] $script:resourcesALL = $script:resourcesALL | Where-Object type -notlike $type
}
else {
[array] $script:resourcesALL = $script:resourcesALL | Where-Object {($_.type -ne $type) -or ($_.name -notin $names)}
}
}
#--------------------------------------------------------------
function get-resourceComponents {
#--------------------------------------------------------------
# gets Azure Resource data from Azure Resource ID string
# examples for $inputString:
# "/subscriptions/mysub/resourceGroups/myrg/providers/Microsoft.Network/virtualNetworks/xxx"
# "/subscriptions/mysub/resourceGroups/myrg/providers/Microsoft.Network/virtualNetworks/xxx/subnets/yyy"
# "[resourceId('Microsoft.Network/virtualNetworks', 'xxx')]"
# "[resourceId('Microsoft.Network/virtualNetworks/subnets', 'xxx, 'yyy')]"
# "[concat(resourceId('Microsoft.Network/virtualNetworks', 'xxx'), '/subnets/yyy')]"
# "[resourceId('Microsoft.Compute/disks', 'disk12')]"
# "[concat(resourceId('Microsoft.Compute/disks', 'disk1'), '2')]" # does not make sense, but found in exported ARM template!
param ( $inputString,
$subscriptionID,
$resourceGroup)
# remove white spaces
$condensedString = $inputString -replace '\s*', '' -replace "'", ''
# process functions
if ($condensedString[0] -eq '[') {
# remove square brackets
if ($condensedString[-1] -ne ']') {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
if ($condensedString.length -le 2) {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
$str = $condensedString.Substring(1,$condensedString.length -2)
# get function
$function, $body = get-functionBody $str $inputString
# function concat
if ($function -eq 'concat') {
# get concat value
$commaPosition = $body.LastIndexOf(',')
if ($commaPosition -lt 1) {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
$head = $body.Substring(0, $commaPosition)
$tail = $body.Substring($commaPosition + 1, $body.length - $commaPosition - 1)
$function, $body = get-functionBody $head $inputString
# converted to function resourceId
if ($function -ne 'resourceId') {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
# concatenated subresource
if ($tail -like '*/*') {
$x, $resType, $resName, $y = $tail -split '/'
if (($Null -ne $x) -or ($Null -eq $resType) -or ($Null -eq $resName) -or ($Null -ne $y)) {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
$str = $body
}
# concatenated string
else {
$str = "$body$tail"
}
}
# function resourceId
elseif ($function -eq 'resourceId') {
$str = $body
}
else {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
# no 3rd. function allowed
if ($str -like '(') {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
$resourceType,$mainResourceName,$subResourceName = $str -split ','
if ($Null -eq $resourceType) {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
if ($Null -eq $mainResourceName) {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
if ($subResourceName.count -gt 1) {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
$resourceArea,$mainResourceType,$subResourceType = $resourceType -split '/'
if ($Null -eq $resourceArea) {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
if ($Null -eq $mainResourceType) {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
if ($subResourceType.count -gt 1) {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
# add concatenated subresource
if ($Null -ne $resType) {
$subResourceType = $resType
$subResourceName = $resName
}
$resID = "/subscriptions/$subscriptionID/resourceGroups/$resourceGroup/providers/$resourceArea/$mainResourceType/$mainResourceName"
if ($Null -ne $subResourceType) {
$resID += "/$subResourceType/$subResourceName"
}
}
# process resource ID
elseif ($condensedString[0] -eq '/') {
$resID = $inputString
$x,$s,$subscriptionID,$r,$resourceGroup,$p,$resourceArea,$mainResourceType,$mainResourceName,$subResourceType,$subResourceName = $resId -split '/'
if ($subResourceName.count -gt 1) {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
}
else {
write-logFileError "Error parsing ARM resource:" `
"$inputString"
}
# new resource function w/o concatenate
$resFunction = "[resourceId('$resourceArea/$mainResourceType"
if ($Null -ne $subResourceType) {
$resFunction += "/$subResourceType"
}
$resFunction += "', '$mainResourceName'"
if ($Null -ne $subResourceType) {
$resFunction += ", '$subResourceName'"
}
$resFunction += ")]"
return @{
resID = $resID
resFunction = $resFunction
subscriptionID = $subscriptionID
resourceGroup = $resourceGroup
resourceArea = $resourceArea
mainResourceType = $mainResourceType
mainResourceName = $mainResourceName
subResourceType = $subResourceType
subResourceName = $subResourceName
}
}
#--------------------------------------------------------------
function test-context{
#--------------------------------------------------------------
param ( $mySub, $mySubUser, $mySubTenant, $myType)
# get context
if ($mySubTenant.length -eq 0) {
$myContext = Get-AzContext -ListAvailable
| Where-Object {$_.Account.Id -eq $mySubUser}
| Where-Object {$_.Subscription.Name -eq $mySub}
}
else {
$myContext = Get-AzContext -ListAvailable
| Where-Object {$_.Account.Id -eq $mySubUser}
| Where-Object {$_.Subscription.Name -eq $mySub}
| Where-Object {$_.Tenant.Id -eq $mySubTenant}
}
if ($Null -eq $myContext) {
write-logFile 'list of existing contexts:'
Get-AzContext -ListAvailable
| Select-Object @{label="AccountId"; expression={$_.Account.Id}}, `
@{label="SubscriptionName"; expression={$_.Subscription.Name}}, `
@{label="TenantId"; expression={$_.Tenant.Id}}
| Tee-Object -FilePath $logPath -append
| Out-Host
write-logFileWarning "Run Connect-AzAccount before starting RGCOPY"
write-logFile
write-logFileError "Get-AzContext failed for user: $mySubUser" `
"Subscription: $mySub" `
"Tenant: $mySubTenant"
}
# set context
set-AzContext -Context $myContext[0] -ErrorAction 'SilentlyContinue' | Out-Null
if (!$?) {
# This should never happen because Get-AzContext already worked:
write-logFileError "Set-AzContext failed for user: $mySubUser" `
"Subscription: $mySub" `
"Tenant: $mySubTenant" `
$error[0]
}
}
#--------------------------------------------------------------
function set-context {
#--------------------------------------------------------------
param ( $mySubscription)
if ($mySubscription -eq $script:currentSub) { return}
write-logFile "--- set subscription context $mySubscription ---" -ForegroundColor DarkGray
if ($mySubscription -eq $sourceSub) {
Set-AzContext -Context $sourceContext -ErrorAction 'SilentlyContinue' | Out-Null
if (!$?) {
# This should never happen because test-context() already worked:
write-logFileError "Could not connect to Subscription '$mySubscription'" `
"Set-AzContext failed" `
'' $error[0]
}
} elseif ($mySubscription -eq $targetSub) {
Set-AzContext -Context $targetContext -ErrorAction 'SilentlyContinue' | Out-Null
if (!$?) {
# This should never happen because test-context() already worked:
write-logFileError "Could not connect to Subscription '$mySubscription'" `
"Set-AzContext failed" `
'' $error[0]
}
} else {
# This should never happen because test-context() already worked:
write-logFileError "Invalid Subscription '$mySubscription'"
}
$script:currentSub = $mySubscription
}
#--------------------------------------------------------------
function get-partTemplate {
#--------------------------------------------------------------
param ( [array] $resIDs,
[string] $resGroup,
[string] $resType)
# get ARM template just for these IDs
$parameter = @{