-
Notifications
You must be signed in to change notification settings - Fork 7
/
build-machine-image.ps1
1939 lines (1893 loc) · 113 KB
/
build-machine-image.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
param (
[Parameter(Mandatory = $true)]
[ValidateSet('amazon', 'azure', 'google')]
[string] $platform,
[Parameter(Mandatory = $true)]
[ValidateSet('win10-64-occ', 'win10-64', 'win10-64-gpu', 'win7-32', 'win7-32-gpu', 'win2012', 'win2019')]
[string] $imageKey,
[string] $group,
[switch] $enableSnapshotCopy = $false,
[switch] $overwrite = $false,
[switch] $disableCleanup = $false
)
function Invoke-OptionalSleep {
param (
[string] $command,
[string] $separator = ' ',
[string] $action = $(
if (($command.Split($separator).Length -gt 1) -and ($command.Split($separator)[1] -in @('in', 'after'))) {
$command.Split($separator)[1]
} else {
$null
}
),
[int] $duration = $(
if (($command.Split($separator).Length -gt 2) -and ($command.Split($separator)[2] -match "^\d+$")) {
[int]$command.Split($separator)[2]
} else {
0
}
),
[string] $unit = $(
if (($command.Split($separator).Length -gt 3) -and ($command.Split($separator)[3] -in @('millisecond', 'milliseconds', 'ms', 'second', 'seconds', 's', 'minute', 'minutes', 'm'))) {
$command.Split($separator)[1]
} else {
'seconds'
}
)
)
begin {
if ($action -and ($duration -gt 0)) {
Write-Output -InputObject ('{0} :: begin - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
}
process {
if ($action -and ($duration -gt 0)) {
Write-Output -InputObject ('{0} :: sleeping for {1} {2}' -f $($MyInvocation.MyCommand.Name), $duration, $unit);
switch -regex ($unit) {
'^(millisecond|milliseconds|ms)$' {
Start-Sleep -Milliseconds $duration;
}
'^(second|seconds|s)$' {
Start-Sleep -Seconds $duration;
}
'^(minute|minutes|m)$' {
Start-Sleep -Seconds ($duration * 60);
}
}
}
}
end {
if ($action -and ($duration -gt 0)) {
Write-Output -InputObject ('{0} :: end - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
}
}
function Get-InstanceStatus {
param (
[string] $instanceName,
[string] $groupName,
[string] $errorAction
)
begin {
Write-Debug -Message ('{0} :: begin - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
process {
$lastStatus = $(if ($errorAction -eq 'SilentlyContinue') { @{ 'Code' = $null; 'Message' = $null; } } else { $null });
try {
$statuses = (Get-AzVm -Name $instanceName -ResourceGroupName $groupName -Status).Statuses;
$lastStatus = $statuses[$statuses.Count - 1];
} catch {
$lastStatus = $(if ($errorAction -eq 'SilentlyContinue') { @{ 'Code' = $null; 'Message' = $null; } } else { $null });
}
return $lastStatus;
}
end {
Write-Debug -Message ('{0} :: end - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
}
function Invoke-BootstrapExecution {
param (
[int] $executionNumber,
[int] $executionCount,
[string] $instanceName,
[string] $groupName,
[object] $execution,
[object] $flow,
[string] $workFolder,
[int] $attemptNumber = 1,
[switch] $disableCleanup = $false
)
begin {
Write-Output -InputObject ('{0} :: begin - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
process {
$instanceStatus = (Get-InstanceStatus -instanceName $instanceName -groupName $groupName);
if (($instanceStatus) -and ($instanceStatus.Code -eq 'PowerState/running')) {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7} has been invoked' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName);
$tokenisedCommandEvaluationErrors = @();
$runCommandScriptContent = [String]::Join('; ', @(
$execution.commands | % {
# tokenised commands (usually commands containing secrets), need to have each of their token values evaluated (eg: to perform a secret lookup)
if ($_.format -and $_.tokens) {
$tokenisedCommand = $_;
try {
($tokenisedCommand.format -f @($tokenisedCommand.tokens | % { (Invoke-Expression -Command $_) } ))
} catch {
$tokenisedCommandEvaluationErrors += @{
'format' = $tokenisedCommand.format;
'tokens' = $tokenisedCommand.tokens;
'exception' = $_.Exception
};
}
} else {
$_
}
}
));
if ($tokenisedCommandEvaluationErrors.Length) {
foreach ($tokenisedCommandEvaluationError in $tokenisedCommandEvaluationErrors) {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}, threw exception evaluating tokenised command (format: "{8}", tokens: "{9}")' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName, $tokenisedCommandEvaluationError.format, [String]::Join(', ', $tokenisedCommandEvaluationError.tokens));
Write-Output -InputObject ($tokenisedCommandEvaluationError.exception.Message);
}
if (-not $disableCleanup) {
Remove-Resource -resourceId $instanceName.Replace('vm-', '') -resourceGroupName $groupName;
}
exit 1;
}
$runCommandScriptPath = ('{0}\{1}.ps1' -f $env:Temp, $execution.name);
Set-Content -Path $runCommandScriptPath -Value $runCommandScriptContent;
switch ($execution.shell) {
'azure-powershell' {
$runCommandResult = (Invoke-AzVMRunCommand `
-ResourceGroupName $groupName `
-VMName $instanceName `
-CommandId 'RunPowerShellScript' `
-ScriptPath $runCommandScriptPath);
Remove-Item -Path $runCommandScriptPath;
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}, has status: {8}' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName, $(if (($runCommandResult) -and ($runCommandResult.Status)) { $runCommandResult.Status.ToLower() } else { '-' }));
if (($runCommandResult.Value) -and ($runCommandResult.Value.Length -gt 0) -and ($runCommandResult.Value[0].Message)) {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}, has std out:' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName);
Write-Output -InputObject $runCommandResult.Value[0].Message;
} else {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}, did not produce output on std out stream' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName);
}
if (($runCommandResult.Value) -and ($runCommandResult.Value.Length -gt 1) -and ($runCommandResult.Value[1].Message)) {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}, has std err:' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName);
Write-Output -InputObject $runCommandResult.Value[1].Message;
} else {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}, did not produce output on std err stream' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName);
}
if (($runCommandResult.Value) -and ($runCommandResult.Value.Length -gt 0)) {
if ($execution.test) {
if ($execution.test.std) {
if ($execution.test.std.out) {
if ($execution.test.std.out.match) {
if ($runCommandResult.Value[0].Message -match $execution.test.std.out.match) {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}, matched: "{8}" in std out' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName, $execution.test.std.out.match);
if ($execution.on.success) {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}, has triggered success action: {8}' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName, $execution.on.success);
switch ($execution.on.success.Split(' ')[0]) {
'reboot' {
Invoke-OptionalSleep -command $execution.on.success;
Restart-AzVM -ResourceGroupName $groupName -Name $instanceName;
}
default {
Write-Output -InputObject ('{0} :: no implementation found for std out regex match success action: {1}' -f $($MyInvocation.MyCommand.Name), $execution.on.success);
}
}
}
} else {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}, did not match: "{8}" in std out' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName, $execution.test.std.out.match);
if ($execution.on.failure) {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}, has triggered failure action: {8}' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName, $execution.on.failure);
switch ($execution.on.failure.Split(' ')[0]) {
'reboot' {
Invoke-OptionalSleep -command $execution.on.failure;
Restart-AzVM -ResourceGroupName $groupName -Name $instanceName;
}
'retry' {
Invoke-OptionalSleep -command $execution.on.failure;
Invoke-BootstrapExecution -executionNumber $executionNumber -executionCount $executionCount -instanceName $instanceName -groupName $groupName -execution $execution -attemptNumber ($attemptNumber + 1) -flow $flow -disableCleanup:$disableCleanup;
}
'retry-task' {
Invoke-OptionalSleep -command $execution.on.failure;
Remove-Resource -resourceId $instanceName.Replace('vm-', '') -resourceGroupName $groupName;
exit 123;
}
'fail' {
Invoke-OptionalSleep -command $execution.on.failure;
if (-not $disableCleanup) {
Remove-Resource -resourceId $instanceName.Replace('vm-', '') -resourceGroupName $groupName;
}
exit 1;
}
default {
Write-Output -InputObject (('{0} :: no implementation found for std out regex match failure action: {1}' -f $($MyInvocation.MyCommand.Name), $execution.on.failure));
}
}
}
}
}
}
if ($execution.test.std.err) {
Write-Output -InputObject (('{0} :: no implementation found for std err test action' -f $($MyInvocation.MyCommand.Name)));
}
}
if ($execution.test.status) {
if ($execution.test.status.code) {
if ($execution.test.status.code.match) {
if ((Get-InstanceStatus -instanceName $instanceName -groupName $groupName -ErrorAction 'SilentlyContinue').Code -match $execution.test.status.code.match) {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}, matched: "{8}" in instance status code' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName, $execution.test.std.out.match);
} else {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}, did not match: "{8}" in instance status code' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName, $execution.test.std.out.match);
# todo: implement results other than 'failure'
if ($execution.on.failure) {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}, has triggered failure action: {8}' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName, $execution.on.failure);
switch ($execution.on.failure.Split(' ')[0]) {
# todo: implement actions other than 'retest'
'retest' {
while ((Get-InstanceStatus -instanceName $instanceName -groupName $groupName -ErrorAction 'SilentlyContinue').Code -notmatch $execution.test.status.code.match) {
Invoke-OptionalSleep -command $execution.on.failure;
}
}
default {
Write-Output -InputObject (('{0} :: no implementation found for std out regex match failure action: {1}' -f $($MyInvocation.MyCommand.Name), $execution.on.failure));
}
}
}
}
}
}
}
}
} else {
$instanceStatus = (Get-InstanceStatus -instanceName $instanceName -groupName $groupName);
if (($instanceStatus) -and ($instanceStatus.Code -eq 'PowerState/stopped')) {
Write-Output -InputObject ('{0} :: instance shutdown detected during bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName);
} elseif (($instanceStatus) -and ($instanceStatus.Code -eq 'PowerState/running')) {
Write-Output -InputObject ('{0} :: running instance state ({1}) detected during bootstrap execution {2}/{3}, attempt {4}; {5}, using shell: {6}, on: {7}/{8}' -f $($MyInvocation.MyCommand.Name), $instanceStatus.Code, $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName);
Publish-Screenshot -instanceName $instanceName -groupName $groupName -platform 'azure' -workFolder $workFolder;
} elseif ($instanceStatus) {
Write-Output -InputObject ('{0} :: unhandled instance state {1} detected during bootstrap execution {2}/{3}, attempt {4}; {5}, using shell: {6}, on: {7}/{8}' -f $($MyInvocation.MyCommand.Name), $instanceStatus.Code, $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName);
} else {
Write-Output -InputObject ('{0} :: missing instance state detected during bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7}' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName);
}
}
}
# bootstrap over winrm for architectures that do not have an azure vm agent
'winrm-powershell' {
$publicIpAddress = (Get-PublicIpAddress -platform $platform -group $groupName -resourceId $resourceId);
if (-not ($publicIpAddress)) {
Write-Output -InputObject ('{0} :: failed to determine public ip address for resource: {1}, in group: {2}, on platform: {3}' -f $($MyInvocation.MyCommand.Name), $resourceId, $groupName, $platform);
exit 1;
} else {
Write-Output -InputObject ('{0} :: public ip address: {1}, found for resource: {2}, in group: {3}, on platform: {4}' -f $($MyInvocation.MyCommand.Name), $publicIpAddress, $resourceId, $groupName, $platform);
}
$adminPassword = (Get-AdminPassword -platform $platform -imageKey $imageKey);
if (-not ($adminPassword)) {
Write-Output -InputObject ('{0} :: failed to determine admin password for image: {1}, on platform: {2}, using: {3}/api/index/v1/task/project.relops.cloud-image-builder.{2}.{1}.latest/artifacts/public/unattend.xml' -f $($MyInvocation.MyCommand.Name), $imageKey, $platform, $env:TASKCLUSTER_ROOT_URL);
exit 1;
} else {
Write-Output -InputObject ('{0} :: admin password for image: {1}, on platform: {2}, found at: {3}/api/index/v1/task/project.relops.cloud-image-builder.{2}.{1}.latest/artifacts/public/unattend.xml' -f $($MyInvocation.MyCommand.Name), $imageKey, $platform, $env:TASKCLUSTER_ROOT_URL);
}
$credential = (New-Object `
-TypeName 'System.Management.Automation.PSCredential' `
-ArgumentList @('.\Administrator', (ConvertTo-SecureString $adminPassword -AsPlainText -Force)));
# modify security group of remote azure instance to allow winrm from public ip of local task instance
try {
$taskRunnerIpAddress = (New-Object Net.WebClient).DownloadString('http://169.254.169.254/latest/meta-data/public-ipv4');
$azNetworkSecurityGroup = (Get-AzNetworkSecurityGroup -Name $flow.name);
$winrmAzNetworkSecurityRuleConfig = (Get-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $azNetworkSecurityGroup -Name 'allow-winrm' -ErrorAction SilentlyContinue);
if ($winrmAzNetworkSecurityRuleConfig) {
$setAzNetworkSecurityRuleConfigResult = (Set-AzNetworkSecurityRuleConfig `
-Name 'allow-winrm' `
-NetworkSecurityGroup $azNetworkSecurityGroup `
-SourceAddressPrefix @(@($taskRunnerIpAddress) + $winrmAzNetworkSecurityRuleConfig.SourceAddressPrefix));
} else {
$winrmRuleFromConfig = @($flow.rules | ? { $_.name -eq 'allow-winrm' })[0];
$setAzNetworkSecurityRuleConfigResult = (Add-AzNetworkSecurityRuleConfig `
-Name $winrmRuleFromConfig.name `
-Description $winrmRuleFromConfig.Description `
-Access $winrmRuleFromConfig.Access `
-Protocol $winrmRuleFromConfig.Protocol `
-Direction $winrmRuleFromConfig.Direction `
-Priority $winrmRuleFromConfig.Priority `
-SourceAddressPrefix @(@($taskRunnerIpAddress) + $winrmRuleFromConfig.SourceAddressPrefix) `
-SourcePortRange $winrmRuleFromConfig.SourcePortRange `
-DestinationAddressPrefix $winrmRuleFromConfig.DestinationAddressPrefix `
-DestinationPortRange $winrmRuleFromConfig.DestinationPortRange);
}
if ($setAzNetworkSecurityRuleConfigResult.ProvisioningState -eq 'Succeeded') {
$updatedIps = @($setAzNetworkSecurityRuleConfigResult.SecurityRules | ? { $_.Name -eq 'allow-winrm' })[0].SourceAddressPrefix;
Write-Output -InputObject ('winrm firewall configuration at: {0}/allow-winrm, modified to allow inbound from: {1}' -f $flow.name, [String]::Join(', ', $updatedIps));
} else {
Write-Output -InputObject ('error: failed to modify winrm firewall configuration. provisioning state: {0}' -f $setAzNetworkSecurityRuleConfigResult.ProvisioningState);
exit 1;
}
} catch {
Write-Output -InputObject ('error: failed to modify winrm firewall configuration. {0}' -f $_.Exception.Message);
exit 1;
}
# enable remoting and add remote azure instance to trusted host list
try {
#Enable-PSRemoting -SkipNetworkProfileCheck -Force
#Write-Output -InputObject 'powershell remoting enabled for session';
& winrm @('set', 'winrm/config/client', '@{AllowUnencrypted="true"}');
Write-Output -InputObject 'winrm-client allow-unencrypted set to: "true"';
$trustedHostsPreBootstrap = (Get-Item -Path 'WSMan:\localhost\Client\TrustedHosts').Value;
Write-Output -InputObject ('winrm-client trusted-hosts detected as: "{0}"' -f $trustedHostsPreBootstrap);
$trustedHostsForBootstrap = $(if (($trustedHostsPreBootstrap) -and ($trustedHostsPreBootstrap.Length -gt 0)) { ('{0},{1}' -f $trustedHostsPreBootstrap, $publicIpAddress) } else { $publicIpAddress });
#Set-Item -Path 'WSMan:\localhost\Client\TrustedHosts' -Value $trustedHostsForBootstrap -Force;
& winrm @('set', 'winrm/config/client', ('@{{TrustedHosts="{0}"}}' -f $trustedHostsForBootstrap));
Write-Output -InputObject ('winrm-client trusted-hosts set to: "{0}"' -f (Get-Item -Path 'WSMan:\localhost\Client\TrustedHosts').Value);
} catch {
Write-Output -InputObject ('error: failed to modify winrm firewall configuration. {0}' -f $_.Exception.Message);
exit 1;
}
$invocationResponse = $null;
$invocationAttempt = 0;
$statuses = (Get-AzVm -Name $instanceName -ResourceGroupName $groupName -Status).Statuses;
$lastStatus = $statuses[$statuses.Count - 1];
do {
$invocationAttempt += 1;
# run remote bootstrap scripts over winrm
try {
$invocationResponse = (Invoke-Command `
-ComputerName $publicIpAddress `
-Credential $credential `
-ScriptBlock { $runCommandScriptContent });
} catch {
Write-Output -InputObject ('error: failed to execute bootstrap commands over winrm on attempt {0}. {1}' -f $invocationAttempt, $_.Exception.Message);
exit 1;
} finally {
if ($invocationResponse) {
Write-Output -InputObject $invocationResponse;
if ($invocationResponse -match 'WinRMOperationTimeout') {
Write-Output -InputObject 'awaiting manual intervention to correct the winrm connection issue';
Start-Sleep -Seconds 120
}
} else {
Write-Output -InputObject ('error: no response received during execution of bootstrap commands over winrm on attempt {0}' -f $invocationAttempt);
}
}
$statuses = (Get-AzVm -Name $instanceName -ResourceGroupName $groupName -Status).Statuses;
$lastStatus = $statuses[$statuses.Count - 1];
Write-Output -InputObject ('{0}/{1} has {2} status tags and last status: {3} ({4})' -f $groupName, $instanceName, $statuses.Count, $lastStatus.DisplayStatus, $lastStatus.Code);
} while (
(
($lastStatus.Code -ne 'PowerState/stopped') -and
($lastStatus.Code -ne 'PowerState/deallocated')
) -and (
# repeat the winrm invocation until it works or the task exceeds its timeout, allowing for manual
# intervention on the host instance to enable the winrm connection or connection issue debugging.
($invocationResponse -eq $null) -or
($invocationResponse -match 'WinRMOperationTimeout')
)
)
# modify azure security group to remove public ip of task instance from winrm exceptions
$allowedIps = @($flow.rules | ? { $_.name -eq 'allow-winrm' })[0].sourceAddressPrefix
$setAzNetworkSecurityRuleConfigResult = (Set-AzNetworkSecurityRuleConfig `
-Name 'allow-winrm' `
-NetworkSecurityGroup $azNetworkSecurityGroup `
-SourceAddressPrefix $allowedIps);
if ($setAzNetworkSecurityRuleConfigResult.ProvisioningState -eq 'Succeeded') {
$updatedIps = @($setAzNetworkSecurityRuleConfigResult.SecurityRules | ? { $_.Name -eq 'allow-winrm' })[0].SourceAddressPrefix;
Write-Output -InputObject ('winrm firewall configuration at: {0}/allow-winrm, reverted to allow inbound from: {1}' -f $flow.name, [String]::Join(', ', $updatedIps));
} else {
Write-Output -InputObject ('error: failed to revert winrm firewall configuration. provisioning state: {0}' -f $setAzNetworkSecurityRuleConfigResult.ProvisioningState);
}
#Set-Item -Path 'WSMan:\localhost\Client\TrustedHosts' -Value $(if (($trustedHostsPreBootstrap) -and ($trustedHostsPreBootstrap.Length -gt 0)) { $trustedHostsPreBootstrap } else { '' }) -Force;
& winrm @('set', 'winrm/config/client', ('@{{TrustedHosts="{0}"}}' -f $trustedHostsPreBootstrap));
Write-Output -InputObject ('winrm-client trusted-hosts reverted to: "{0}"' -f (Get-Item -Path 'WSMan:\localhost\Client\TrustedHosts').Value);
& winrm @('set', 'winrm/config/client', '@{AllowUnencrypted="false"}');
Write-Output -InputObject 'winrm-client allow-unencrypted reverted to: "false"';
}
}
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7} has been completed' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName);
} else {
Write-Output -InputObject ('{0} :: bootstrap execution {1}/{2}, attempt {3}; {4}, using shell: {5}, on: {6}/{7} has been skipped. instance is not running.' -f $($MyInvocation.MyCommand.Name), $executionNumber, $executionCount, $attemptNumber, $execution.name, $execution.shell, $groupName, $instanceName);
}
}
end {
Write-Output -InputObject ('{0} :: end - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
}
function Invoke-BootstrapExecutions {
param (
[string] $instanceName,
[string] $groupName,
[object[]] $executions,
[object] $flow,
[switch] $disableCleanup = $false
)
begin {
Write-Output -InputObject ('{0} :: begin - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
process {
if ($executions -and $executions.Length) {
$executionNumber = 1;
Write-Output -InputObject ('{0} :: detected {1} bootstrap command execution configurations for: {2}/{3}' -f $($MyInvocation.MyCommand.Name), $executions.Length, $groupName, $instanceName);
foreach ($execution in $executions) {
Invoke-BootstrapExecution -executionNumber $executionNumber -executionCount $executions.Length -instanceName $instanceName -groupName $groupName -execution $execution -flow $flow -disableCleanup:$disableCleanup;
$executionNumber += 1;
}
}
}
end {
Write-Output -InputObject ('{0} :: end - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
}
function Remove-Resource {
param (
[string] $resourceId,
[string] $resourceGroupName,
[string[]] $resourceNames = @(
('cib-{0}' -f $resourceId),
('vm-{0}' -f $resourceId),
('ni-{0}' -f $resourceId),
('ip-{0}' -f $resourceId),
('disk-{0}*' -f $resourceId)
)
)
begin {
Write-Output -InputObject ('{0} :: begin - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
process {
# instance instantiation failures leave behind a disk, public ip and network interface which need to be deleted.
# the deletion will fail if the failed instance deletion is not complete.
# retry for a while before giving up.
do {
foreach ($resourceName in $resourceNames) {
$resourceType = @{
'cib' = 'virtual machine';
'vm' = 'virtual machine';
'ni' = 'network interface';
'ip' = 'public ip address';
'disk' = 'disk'
}[$resourceName.Split('-')[0]];
switch ($resourceType) {
'virtual machine' {
$resource = (Get-AzVM `
-ResourceGroupName $resourceGroupName `
-Name $resourceName `
-ErrorAction SilentlyContinue);
if (($resource) -and ($resource.Name -eq $resourceName)) {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal attempt started...' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resource.Name));
try {
$operation = (Remove-AzVm `
-ResourceGroupName $resourceGroupName `
-Name $resourceName `
-Force `
-ErrorAction SilentlyContinue);
if ($operation.Status -eq 'Succeeded') {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal appears successful' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resourceName));
} else {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal failed with status: {4}. {5}' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resourceName, $operation.Status, $operation.Error));
}
} catch {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal threw exception. {4}' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resourceName, $_.Exception.Message));
}
} else {
Write-Output -InputObject (('{0} :: {1}: {2}/{3} not found. removal skipped' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resourceName));
}
}
'network interface' {
$resource = (Get-AzNetworkInterface `
-ResourceGroupName $resourceGroupName `
-Name $resourceName `
-ErrorAction SilentlyContinue);
if (($resource) -and ($resource.Name -eq $resourceName)) {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal attempt started...' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resource.Name));
try {
$operation = (Remove-AzNetworkInterface `
-ResourceGroupName $resourceGroupName `
-Name $resourceName `
-Force `
-ErrorAction SilentlyContinue);
if ($operation.Status -eq 'Succeeded') {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal appears successful' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resourceName));
} else {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal failed with status: {4}. {5}' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resourceName, $operation.Status, $operation.Error));
}
} catch {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal threw exception. {4}' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resourceName, $_.Exception.Message));
}
} else {
Write-Output -InputObject (('{0} :: {1}: {2}/{3} not found. removal skipped' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resourceName));
}
}
'public ip address' {
$resource = (Get-AzPublicIpAddress `
-ResourceGroupName $resourceGroupName `
-Name $resourceName `
-ErrorAction SilentlyContinue);
if (($resource) -and ($resource.Name -eq $resourceName)) {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal attempt started...' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resource.Name));
try {
$operation = (Remove-AzPublicIpAddress `
-ResourceGroupName $resourceGroupName `
-Name $resourceName `
-Force `
-ErrorAction SilentlyContinue);
if ($operation.Status -eq 'Succeeded') {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal appears successful' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resourceName));
} else {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal failed with status: {4}. {5}' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resourceName, $operation.Status, $operation.Error));
}
} catch {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal threw exception. {4}' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resourceName, $_.Exception.Message));
}
} else {
Write-Output -InputObject (('{0} :: {1}: {2}/{3} not found. removal skipped' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resourceName));
}
}
'disk' {
$resource = (Get-AzDisk `
-ResourceGroupName $resourceGroupName `
-DiskName $resourceName `
-ErrorAction SilentlyContinue);
if (($resource) -and ($resource.Name -eq $resourceName)) {
foreach ($azDisk in @(Get-AzDisk -ResourceGroupName $resourceGroupName -DiskName $resourceName -ErrorAction SilentlyContinue)) {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal attempt started...' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $azDisk.Name));
try {
$operation = (Remove-AzDisk `
-ResourceGroupName $resourceGroupName `
-DiskName $azDisk.Name `
-Force `
-ErrorAction SilentlyContinue);
if ($operation.Status -eq 'Succeeded') {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal appears successful' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $azDisk.Name));
} else {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal failed with status: {4}. {5}' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $azDisk.Name, $operation.Status, $operation.Error));
}
} catch {
Write-Output -InputObject (('{0} :: {1}: {2}/{3}, removal threw exception. {4}' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $azDisk.Name, $_.Exception.Message));
}
}
} else {
Write-Output -InputObject (('{0} :: {1}: {2}/{3} not found. removal skipped' -f $($MyInvocation.MyCommand.Name), $resourceType, $resourceGroupName, $resourceName));
}
}
}
}
} while (
(
(Get-AzVM -ResourceGroupName $resourceGroupName -Name ('cib-{0}' -f $resourceId) -ErrorAction SilentlyContinue) -and
((Get-AzVM -ResourceGroupName $resourceGroupName -Name ('cib-{0}' -f $resourceId) -ErrorAction SilentlyContinue).Name -eq ('cib-{0}' -f $resourceId))
) -or
(
(Get-AzVM -ResourceGroupName $resourceGroupName -Name ('vm-{0}' -f $resourceId) -ErrorAction SilentlyContinue) -and
((Get-AzVM -ResourceGroupName $resourceGroupName -Name ('vm-{0}' -f $resourceId) -ErrorAction SilentlyContinue).Name -eq ('vm-{0}' -f $resourceId))
) -or
(
(Get-AzNetworkInterface -ResourceGroupName $resourceGroupName -Name ('ni-{0}' -f $resourceId) -ErrorAction SilentlyContinue) -and
((Get-AzNetworkInterface -ResourceGroupName $resourceGroupName -Name ('ni-{0}' -f $resourceId) -ErrorAction SilentlyContinue).Name -eq ('ni-{0}' -f $resourceId))
) -or
(
(Get-AzPublicIpAddress -ResourceGroupName $resourceGroupName -Name ('ip-{0}' -f $resourceId) -ErrorAction SilentlyContinue) -and
((Get-AzPublicIpAddress -ResourceGroupName $resourceGroupName -Name ('ip-{0}' -f $resourceId) -ErrorAction SilentlyContinue).Name -eq ('ip-{0}' -f $resourceId))
) -or
(
(Get-AzDisk -ResourceGroupName $resourceGroupName -DiskName ('disk-{0}*' -f $resourceId) -ErrorAction SilentlyContinue) -and
((Get-AzDisk -ResourceGroupName $resourceGroupName -DiskName ('disk-{0}*' -f $resourceId) -ErrorAction SilentlyContinue).Name -eq ('disk-{0}*' -f $resourceId))
)
)
}
end {
Write-Output -InputObject ('{0} :: end - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
}
function Update-RequiredModules {
param (
[string] $repository = 'PSGallery',
[hashtable[]] $requiredModules = @(
@{
'module' = 'Az.Compute';
'version' = '3.1.0'
},
@{
'module' = 'Az.Network';
'version' = '2.1.0'
},
@{
'module' = 'Az.Resources';
'version' = '1.8.0'
},
@{
'module' = 'Az.Storage';
'version' = '1.9.0'
},
@{
'module' = 'posh-minions-managed';
'version' = '0.0.126'
},
@{
'module' = 'powershell-yaml';
'version' = '0.4.1'
}
)
)
begin {
Write-Output -InputObject ('{0} :: begin - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
Write-Output -InputObject ('{0} :: installed module version observations (before updates):' -f $($MyInvocation.MyCommand.Name));
foreach ($m in (Get-Module)) {
Write-Output -InputObject ('{0} :: {1} - {2}' -f $($MyInvocation.MyCommand.Name), $m.Name, $m.Version);
}
}
process {
if (@(Get-PSRepository -Name $repository)[0].InstallationPolicy -ne 'Trusted') {
try {
Set-PSRepository -Name $repository -InstallationPolicy 'Trusted';
Write-Output -InputObject ('{0} :: setting of installation policy to trusted for repository: {1}, succeeded' -f $($MyInvocation.MyCommand.Name), $repository);
} catch {
Write-Output -InputObject ('{0} :: setting of installation policy to trusted for repository: {1}, failed. {2}' -f $($MyInvocation.MyCommand.Name), $repository, $_.Exception.Message);
}
}
foreach ($rm in $requiredModules) {
$module = (Get-Module -Name $rm.module -ErrorAction SilentlyContinue);
if ($module) {
if ($module.Version -lt $rm.version) {
try {
Update-Module -Name $rm.module -RequiredVersion $rm.version;
Write-Output -InputObject ('{0} :: update of required module: {1}, version: {2}, succeeded' -f $($MyInvocation.MyCommand.Name), $rm.module, $rm.version);
} catch {
Write-Output -InputObject ('{0} :: update of required module: {1}, version: {2}, failed. {3}' -f $($MyInvocation.MyCommand.Name), $rm.module, $rm.version, $_.Exception.Message);
}
}
} else {
try {
Install-Module -Name $rm.module -RequiredVersion $rm.version -AllowClobber;
Write-Output -InputObject ('{0} :: install of required module: {1}, version: {2}, succeeded' -f $($MyInvocation.MyCommand.Name), $rm.module, $rm.version);
} catch {
Write-Output -InputObject ('{0} :: install of required module: {1}, version: {2}, failed. {3}' -f $($MyInvocation.MyCommand.Name), $rm.module, $rm.version, $_.Exception.Message);
}
}
try {
Import-Module -Name $rm.module -RequiredVersion $rm.version -ErrorAction SilentlyContinue;
Write-Output -InputObject ('{0} :: import of required module: {1}, version: {2}, succeeded' -f $($MyInvocation.MyCommand.Name), $rm.module, $rm.version);
} catch {
Write-Output -InputObject ('{0} :: import of required module: {1}, version: {2}, failed. {3}' -f $($MyInvocation.MyCommand.Name), $rm.module, $rm.version, $_.Exception.Message);
# if we get here, the instance is borked and will throw exceptions on all subsequent tasks.
& shutdown @('/s', '/t', '3', '/c', 'borked powershell module library detected', '/f', '/d', '1:1');
exit 123;
}
}
}
end {
Write-Output -InputObject ('{0} :: installed module version observations (after updates):' -f $($MyInvocation.MyCommand.Name));
foreach ($m in (Get-Module)) {
Write-Output -InputObject ('{0} :: {1} - {2}' -f $($MyInvocation.MyCommand.Name), $m.Name, $m.Version);
}
Write-Output -InputObject ('{0} :: end - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
}
function Initialize-Platform {
param (
[string] $platform,
[object] $secret
)
begin {
Write-Output -InputObject ('{0} :: begin - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
process {
switch ($platform) {
'azure' {
try {
Connect-AzAccount `
-ServicePrincipal `
-Credential (New-Object System.Management.Automation.PSCredential($secret.azure_gamma.app_id, (ConvertTo-SecureString `
-String $secret.azure_gamma.password `
-AsPlainText `
-Force))) `
-TenantId $secret.azure_gamma.tenant_id `
-SubscriptionId $secret.azure_gamma.subscription_id | Out-Null;
Set-AzContext `
-TenantId $secret.azure_gamma.tenant_id `
-SubscriptionId $secret.azure_gamma.subscription_id | Out-Null;
Write-Output -InputObject ('{0} :: for platform: {1}, setting of credentials, succeeded' -f $($MyInvocation.MyCommand.Name), $platform);
} catch {
Write-Output -InputObject ('{0} :: for platform: {1}, setting of credentials, failed. {2}' -f $($MyInvocation.MyCommand.Name), $platform, $_.Exception.Message);
}
try {
$azcopyExePath = ('{0}\azcopy.exe' -f $workFolder);
$azcopyZipPath = ('{0}\azcopy.zip' -f $workFolder);
$azcopyZipUrl = 'https://aka.ms/downloadazcopy-v10-windows';
if (-not (Test-Path -Path $azcopyExePath -ErrorAction SilentlyContinue)) {
(New-Object Net.WebClient).DownloadFile($azcopyZipUrl, $azcopyZipPath);
if (Test-Path -Path $azcopyZipPath -ErrorAction SilentlyContinue) {
Write-Output -InputObject ('{0} :: downloaded: {1} from: {2}' -f $($MyInvocation.MyCommand.Name), $azcopyZipPath, $azcopyZipUrl);
Expand-Archive -Path $azcopyZipPath -DestinationPath $workFolder;
try {
$extractedAzcopyExePath = (@(Get-ChildItem -Path ('{0}\azcopy.exe' -f $workFolder) -Recurse -ErrorAction SilentlyContinue -Force)[0].FullName);
Write-Output -InputObject ('{0} :: extracted: {1} from: {2}' -f $($MyInvocation.MyCommand.Name), $extractedAzcopyExePath, $azcopyZipPath);
Copy-Item -Path $extractedAzcopyExePath -Destination $azcopyExePath;
if (Test-Path -Path $azcopyExePath -ErrorAction SilentlyContinue) {
Write-Output -InputObject ('{0} :: copied: {1} to: {2}' -f $($MyInvocation.MyCommand.Name), $extractedAzcopyExePath, $azcopyExePath);
$env:PATH = ('{0};{1}' -f $env:PATH, $workFolder);
[Environment]::SetEnvironmentVariable('PATH', $env:PATH, 'User');
Write-Output -InputObject ('{0} :: user env PATH set to: {1}' -f $($MyInvocation.MyCommand.Name), $env:PATH);
}
} catch {
Write-Output -InputObject ('{0} :: failed to extract azcopy from: {1}' -f $($MyInvocation.MyCommand.Name), $azcopyZipPath);
}
} else {
Write-Output -InputObject ('{0} :: failed to download: {1} from: {2}' -f $($MyInvocation.MyCommand.Name), $azcopyZipPath, $azcopyZipUrl);
exit 123;
}
}
Write-Output -InputObject ('{0} :: for platform: {1}, acquire of platform tools, succeeded' -f $($MyInvocation.MyCommand.Name), $platform);
} catch {
Write-Output -InputObject ('{0} :: for platform: {1}, acquire of platform tools, failed. {2}' -f $($MyInvocation.MyCommand.Name), $platform, $_.Exception.Message);
}
}
'amazon' {
try {
Set-AWSCredential `
-AccessKey $secret.amazon.id `
-SecretKey $secret.amazon.key `
-StoreAs 'default' | Out-Null;
Write-Output -InputObject ('{0} :: on platform: {1}, setting of credentials, succeeded' -f $($MyInvocation.MyCommand.Name), $platform);
} catch {
Write-Output -InputObject ('{0} :: on platform: {1}, setting of credentials, failed. {2}' -f $($MyInvocation.MyCommand.Name), $platform, $_.Exception.Message);
}
}
}
}
end {
Write-Output -InputObject ('{0} :: end - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
}
function Get-ImageArtifactDescriptor {
param (
[string] $platform,
[string] $imageKey,
[string] $uri = ('{0}/api/index/v1/task/project.relops.cloud-image-builder.{1}.{2}.latest/artifacts/public/image-bucket-resource.json' -f $env:TASKCLUSTER_ROOT_URL, $platform, $imageKey)
)
begin {
Write-Debug -Message ('{0} :: begin - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
process {
$imageArtifactDescriptor = $null;
try {
$memoryStream = (New-Object System.IO.MemoryStream(, (New-Object System.Net.WebClient).DownloadData($uri)));
$streamReader = (New-Object System.IO.StreamReader(New-Object System.IO.Compression.GZipStream($memoryStream, [System.IO.Compression.CompressionMode] 'Decompress')));
$imageArtifactDescriptor = ($streamReader.ReadToEnd() | ConvertFrom-Json);
Write-Debug -Message ('{0} :: disk image config for: {1}, on {2}, fetch and extraction from: {3}, suceeded' -f $($MyInvocation.MyCommand.Name), $imageKey, $platform, $uri);
} catch {
Write-Output -Message ('{0} :: disk image config for: {1}, on {2}, fetch and extraction from: {3}, failed. {4}' -f $($MyInvocation.MyCommand.Name), $imageKey, $platform, $uri, $_.Exception.Message);
exit 1
}
return $imageArtifactDescriptor;
}
end {
Write-Debug -Message ('{0} :: end - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
}
function Invoke-SnapshotCopy {
param (
[string] $platform,
[string] $imageKey,
[object] $target,
[string] $targetImageName,
[object] $imageArtifactDescriptor,
[string] $targetSnapshotName = ('{0}-{1}-{2}' -f $target.group.Replace('rg-', ''), $imageKey, $imageArtifactDescriptor.build.revision.Substring(0, 7))
)
begin {
Write-Output -InputObject ('{0} :: begin - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
process {
# check if the image snapshot exists in another regional resource-group
foreach ($source in @($config.target | ? { (($_.platform -eq $platform) -and $_.group -ne $group) })) {
$sourceSnapshotName = ('{0}-{1}-{2}' -f $source.group.Replace('rg-', ''), $imageKey, $imageArtifactDescriptor.build.revision.Substring(0, 7));
$sourceSnapshot = (Get-AzSnapshot `
-ResourceGroupName $source.group `
-SnapshotName $sourceSnapshotName `
-ErrorAction SilentlyContinue);
if ($sourceSnapshot) {
Write-Output -InputObject ('{0} :: found snapshot: {1}, in group: {2}, in cloud platform: {3}. triggering machine copy from {2} to {4}...' -f $($MyInvocation.MyCommand.Name), $sourceSnapshotName, $source.group, $source.platform, $target.group);
# get/create storage account in target region
$storageAccountName = ('{0}cib' -f $target.group.Replace('rg-', '').Replace('-', ''));
$targetAzStorageAccount = (Get-AzStorageAccount `
-ResourceGroupName $target.group `
-Name $storageAccountName);
if ($targetAzStorageAccount) {
Write-Output -InputObject ('{0} :: detected storage account: {1}, for resource group: {2}' -f $($MyInvocation.MyCommand.Name), $storageAccountName, $target.group);
} else {
$targetAzStorageAccount = (New-AzStorageAccount `
-ResourceGroupName $target.group `
-AccountName $storageAccountName `
-Location $target.region.Replace(' ', '').ToLower() `
-SkuName 'Standard_LRS');
Write-Output -InputObject ('{0} :: created storage account: {1}, for resource group: {2}' -f $($MyInvocation.MyCommand.Name), $storageAccountName, $target.group);
}
if (-not ($targetAzStorageAccount)) {
Write-Output -InputObject ('{0} :: failed to get or create az storage account: {1}' -f $($MyInvocation.MyCommand.Name), $storageAccountName);
exit 1;
}
# get/create storage container (bucket) in target region
$storageContainerName = ('{0}cib' -f $target.group.Replace('rg-', '').Replace('-', ''));
$targetAzStorageContainer = (Get-AzStorageContainer `
-Name $storageContainerName `
-Context $targetAzStorageAccount.Context);
if ($targetAzStorageContainer) {
Write-Output -InputObject ('{0} :: detected storage container: {1}' -f $($MyInvocation.MyCommand.Name), $storageContainerName);
} else {
$targetAzStorageContainer = (New-AzStorageContainer `
-Name $storageContainerName `
-Context $targetAzStorageAccount.Context `
-Permission 'Container');
Write-Output -InputObject ('{0} :: created storage container: {1}' -f $($MyInvocation.MyCommand.Name), $storageContainerName);
}
if (-not ($targetAzStorageContainer)) {
Write-Output -InputObject ('{0} :: failed to get or create az storage container: {1}' -f $($MyInvocation.MyCommand.Name), $storageContainerName);
exit 1;
}
# copy snapshot to target container (bucket)
$sourceAzSnapshotAccess = (Grant-AzSnapshotAccess `
-ResourceGroupName $source.group `
-SnapshotName $sourceSnapshotName `
-DurationInSecond 3600 `
-Access 'Read');
Start-AzStorageBlobCopy `
-AbsoluteUri $sourceAzSnapshotAccess.AccessSAS `
-DestContainer $storageContainerName `
-DestContext $targetAzStorageAccount.Context `
-DestBlob $targetSnapshotName;
# todo: wrap above cmdlet in try/catch and handle exceptions
$targetAzStorageBlobCopyState = (Get-AzStorageBlobCopyState `
-Container $storageContainerName `
-Blob $targetSnapshotName `
-Context $targetAzStorageAccount.Context `
-WaitForComplete);
$targetAzSnapshotConfig = (New-AzSnapshotConfig `
-AccountType 'Standard_LRS' `
-OsType 'Windows' `
-Location $target.region.Replace(' ', '').ToLower() `
-CreateOption 'Import' `
-SourceUri ('{0}{1}/{2}' -f $targetAzStorageAccount.Context.BlobEndPoint, $storageContainerName, $targetSnapshotName) `
-StorageAccountId $targetAzStorageAccount.Id);
$targetAzSnapshot = (New-AzSnapshot `
-ResourceGroupName $target.group `
-SnapshotName $targetSnapshotName `
-Snapshot $targetAzSnapshotConfig);
Write-Output -InputObject ('{0} :: provisioning of snapshot: {1}, has state: {2}' -f $($MyInvocation.MyCommand.Name), $targetSnapshotName, $targetAzSnapshot.ProvisioningState.ToLower());
$targetAzImageConfig = (New-AzImageConfig `
-Location $target.region.Replace(' ', '').ToLower());
$targetAzImageConfig = (Set-AzImageOsDisk `
-Image $targetAzImageConfig `
-OsType 'Windows' `
-OsState 'Generalized' `
-SnapshotId $targetAzSnapshot.Id);
$targetAzImage = (New-AzImage `
-ResourceGroupName $target.group `
-ImageName $targetImageName `
-Image $targetAzImageConfig);
if (-not $targetAzImage) {
Write-Output -InputObject ('{0} :: provisioning of image: {1}, failed' -f $($MyInvocation.MyCommand.Name), $targetImageName);
exit 1;
}
Write-Output -InputObject ('{0} :: provisioning of image: {1}, has state: {2}' -f $($MyInvocation.MyCommand.Name), $targetImageName, $targetAzImage.ProvisioningState.ToLower());
exit;
}
}
}
end {
Write-Output -InputObject ('{0} :: end - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
}
function Get-AzureSkuFamily {
param (
[string] $sku
)
begin {
Write-Debug -Message ('{0} :: begin - {1:o}' -f $($MyInvocation.MyCommand.Name), (Get-Date).ToUniversalTime());
}
process {
switch -regex ($sku) {
'^Basic_A[0-9]+$' {
$skuFamily = 'Basic A Family vCPUs';
break;
}
'^Standard_A[0-7]$' {
$skuFamily = 'Standard A0-A7 Family vCPUs';
break;
}
'^Standard_A(8|9|10|11)$' {
$skuFamily = 'Standard A8-A11 Family vCPUs';
break;
}
'^(Basic|Standard)_(B|D|E|F|H|L|M)[0-9]+m?r?$' {
$skuFamily = '{0} {1} Family vCPUs' -f $matches[1], $matches[2];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)[0-9]+m?r?_Promo$' {
$skuFamily = '{0} {1} Promo Family vCPUs' -f $matches[1], $matches[2];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)[0-9]+[lmt]?s$' {
$skuFamily = '{0} {1}S Family vCPUs' -f $matches[1], $matches[2];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M|P)([BC])[0-9]+r?s$' {
$skuFamily = '{0} {1}{2}S Family vCPUs' -f $matches[1], $matches[2], $matches[3];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)[0-9]+(-(1|2|4|8|16|32|64))?m?s$' {
$skuFamily = '{0} {1}S Family vCPUs' -f $matches[1], $matches[2];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)S[0-9]+$' {
$skuFamily = '{0} {1}S Family vCPUs' -f $matches[1], $matches[2];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)1?[0-9]+m?_v([2-4])$' {
$skuFamily = '{0} {1}v{2} Family vCPUs' -f $matches[1], $matches[2], $matches[3];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)?[0-9]+_v([2-4])_Promo$' {
$skuFamily = '{0} {1}v{2} Promo Family vCPUs' -f $matches[1], $matches[2], $matches[3];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)1?[0-9]+_v([2-4])$' {
$skuFamily = '{0} {1}v{2} Family vCPUs' -f $matches[1], $matches[2], $matches[3];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)1?[0-9]+m?s_v([2-4])$' {
$skuFamily = '{0} {1}Sv{2} Family vCPUs' -f $matches[1], $matches[2], $matches[3];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)[0-9]+(-(1|2|4|8|16|32|64))?s_v([2-4])$' {
$skuFamily = '{0} {1}Sv{2} Family vCPUs' -f $matches[1], $matches[2], $matches[5];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)S[0-9]+(-(1|2|4|8|16|32|64))?_v([2-4])$' {
$skuFamily = '{0} {1}Sv{2} Family vCPUs' -f $matches[1], $matches[2], $matches[5];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)[0-9]+(-(1|2|4|8|16|32|64))?i_v([2-4])$' {
$skuFamily = '{0} {1}Iv{2} Family vCPUs' -f $matches[1], $matches[2], $matches[5];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)[0-9]+(-(1|2|4|8|16|32|64))?is_v([2-4])$' {
$skuFamily = '{0} {1}ISv{2} Family vCPUs' -f $matches[1], $matches[2], $matches[5];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)S[0-9]+_v([2-4])_Promo$' {
$skuFamily = '{0} {1}Sv{2} Promo Family vCPUs' -f $matches[1], $matches[2], $matches[3];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)1?[0-9]+a_v([2-4])$' {
$skuFamily = '{0} {1}Av{2} Family vCPUs' -f $matches[1], $matches[2], $matches[3];
break;
}
'^(Basic|Standard)_(A|B|D|E|F|H|L|M)1?[0-9]+as_v([2-4])$' {
$skuFamily = '{0} {1}ASv{2} Family vCPUs' -f $matches[1], $matches[2], $matches[3];
break;
}
'^Standard_N([CV])[0-9]+r?$' {
$skuFamily = 'Standard N{0} Family vCPUs' -f $matches[1];
break;
}
'^Standard_N([CV])[0-9]+r?_Promo$' {
$skuFamily = 'Standard N{0} Promo Family vCPUs' -f $matches[1];
break;
}
'^Standard_N([DP])S[0-9]+$' {
$skuFamily = 'Standard N{0}S Family vCPUs' -f $matches[1];
break;
}