/
ConfigASDK.ps1
4493 lines (4086 loc) · 291 KB
/
ConfigASDK.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
<#
.SYNOPSYS
The purpose of this script is to automate as much as possible post deployment tasks in Azure Stack Development Kit
This includes:
* Validates all input parameters
* Installs Azure Stack PowerShell and AzureRM modules
* Ensures password for VMs meets complexity required for App Service installation
* Updated password expiration (180 days)
* Disable Windows Update on all infrastructures VMs and ASDK host (To avoid the temptation to apply the patches...)
* Tools installation (Azure Stack Tools)
* Registration of the ASDK to Azure (Optional - enables Marketplace Syndication)
* Windows Server 2016 Datacenter Evaluation (Full + Core) images added to the Platform Image Repository
* Ubuntu Server 16.04-LTS image added to the Platform Image Repository
* Corresponding gallery items created in the Marketplace for the Windows Server and Ubuntu Server images
* Gallery item created for MySQL 5.7 and SQL Server 2017 (both on Ubuntu Server 16.04 LTS)
* Automates adding of Microsoft VM Extensions to Gallery from Marketplace (for registered ASDKs)
* MySQL Resource Provider installation
* SQL Server Resource Provider installation
* Deployment of a MySQL 5.7 hosting server on Ubuntu Server 16.04 LTS
* Deployment of a SQL Server 2017 hosting server on Ubuntu Server 16.04 LTS
* Adding SQL Server & MySQL hosting servers to Resource Providers including SKU/Quotas
* App Service prerequisites installation (SQL Server PowerShell, SQL Server DB VM and Standalone File Server)
* App Service Resource Provider sources download and certificates generation
* App Service Service Principal Created (for Azure AD and ADFS)
* Grants App Service Service Principal Admin Consent (for Azure AD)
* Automates deployment of the latest App Service release using dynamically constructed JSON
* Set new default Quotas for MySQL, SQL Server, Compute, Network, Storage and Key Vault
* Creates a Base Plan and Offer containing all deployed services
* Creates a user subscription for the logged in tenant, and activates all resource providers
* Installs a selection of useful apps via Chocolatey (Putty, Chrome, VS Code, WinDirStat, WinSCP, Python3)
* Configures Python & Azure CLI for usage with ASDK
* MySQL, SQL, App Service and Host Customization can be optionally skipped
* Cleans up download folder to ensure clean future runs
* Transcript Log for errors and troubleshooting
* Progress Tracking and rerun reliability with ConfigASDkProgress.csv file
* Stores script output in a ConfigASDKOutput.txt, for future reference
* Supports usage in offline/disconnected environments
.VERSION
1808.1 Added fix for BITS issues with MySQL/SQL RP installations
1808 No longer adds VMSS gallery item as this is built in.
Updated to support ASDK build 1.1808.0.97
1807.1 Updated to support automatic downloading of Microsoft VM Extensions for registered ASDKs
Added SQL Server PowerShell installation to configure App Service SQL Server VM with Contained DB Authentication
1807 Updated to provide support for offline deployments, using zip file containing pre-downloaded binaries, tools and scripts along with PS 1.4.0 support
Also added support for Azure CLI and Python configuration
1805.2 Update to Windows Image creation to handle adding of KB4132216 to update Servicing Stack (for build 14393) for future updates
(<https://support.microsoft.com/en-us/help/4132216>)
1805.1 Updates to handling Azure subscriptions with multiple Azure AD tenants, and error handling for random Add-AzureRmVhd pipeline error,
added automated App Service quota to base plan, created user subscription and activated RPs for that subscription.
1805 Updated with improvements to Azure account verification, ability to skip RP deployment, run counters and bug fixes
1804 Updated with support for ASDK 1804 and PowerShell 1.3.0, bug fixes, reduced number of modules imported from GitHub tools repo
3.1 Update added App Service automation, bug fixes, MySQL Root account fix.
3.0 Major update for ASDK release 20180329.1
2.0 Update for release 1.0.280917.3
1.0: Small bug fixes and adding quotas/plan/offer creation
0.5: Add SQL 2014 VM deployment
0.4: Add Windows update disable
0.3: Bug fix (SQL Provider prompting for tenantdirectoryID)
0.2: Bug Fix (AZStools download)
.AUTHOR
Matt McSpirit
Blog: http://www.mattmcspirit.com
Email: matt.mcspirit@microsoft.com
Twitter: @mattmcspirit
.CREDITS
Jon LaBelle - https://jonlabelle.com/snippets/view/powershell/download-remote-file-with-retry-support
Alain Vetier - https://github.com/esache/Azure-Stack
Ned Ballavance - https://github.com/ned1313/AzureStack-VM-PoC
Rik Hepworth - https://github.com/rikhepworth/azurestack
.GUIDANCE
Please refer to the Readme.md (https://github.com/mattmcspirit/azurestack/blob/master/deployment/README.md) for recommended
deployment parameter usage and instructions.
#>
#####################################################################################################
# This sample script is not supported under any Microsoft standard support program or service. #
# The sample script is provided AS IS without warranty of any kind. Microsoft further disclaims #
# all implied warranties including, without limitation, any implied warranties of merchantability #
# or of fitness for a particular purpose. The entire risk arising out of the use or performance of #
# the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, #
# or anyone else involved in the creation, production, or delivery of the scripts be liable for any #
# damages whatsoever (including, without limitation, damages for loss of business profits, business #
# interruption, loss of business information, or other pecuniary loss) arising out of the use of or #
# inability to use the sample scripts or documentation, even if Microsoft has been advised of the #
# possibility of such damages #
#####################################################################################################
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[String] $azureDirectoryTenantName,
[Parameter(Mandatory = $true)]
[ValidateSet("AzureAd", "ADFS")]
[String] $authenticationType,
# Path to store downloaded files
[parameter(Mandatory = $true)]
[String]$downloadPath,
# Path to Windows Server 2016 Datacenter Evaluation ISO file
[parameter(Mandatory = $false)]
[String]$ISOPath,
# Password used for deployment of the ASDK.
[parameter(Mandatory = $false)]
[String]$azureStackAdminPwd,
# Provide Local Administrator password for App Service, MySQL and SQL VMs.
[parameter(Mandatory = $false)]
[String]$VMpwd,
# Username for Azure AD Login - username@<directoryname>.onmicrosoft.com
[parameter(Mandatory = $false)]
[string]$azureAdUsername,
# Password for Azure AD login
[parameter(Mandatory = $false)]
[string]$azureAdPwd,
# If you want the script to register the ASDK for you, use this flag
[switch]$registerASDK,
# If you want to use the same Azure AD creds that you used to deploy Azure Stack, to register it, set this flag
[switch]$useAzureCredsForRegistration,
# Username for Azure Subscription Login for registering Azure Stack - username@<directoryname>.onmicrosoft.com
[parameter(Mandatory = $false)]
[string]$azureRegUsername,
# Password for Azure Subscription Login for registering Azure Stack
[parameter(Mandatory = $false)]
[string]$azureRegPwd,
# Azure Subscription to be used for registering Azure Stack
[parameter(Mandatory = $false)]
[string]$azureRegSubId,
# If you don't want to install the MySQL Resource Provider and Hosting Server set this flag
[switch]$skipMySQL,
# If you don't want to install the SQL Server Resource Provider and Hosting Server set this flag
[switch]$skipMSSQL,
# If you don't want to install the App Service and pre-requisites set this flag
[switch]$skipAppService,
# If you don't want to customize the ASDK host with useful apps such as Chrome, Azure CLI, VS Code etc. set this flag
[switch]$skipCustomizeHost,
# Offline installation package path for all key components
[parameter(Mandatory = $false)]
[string]$configAsdkOfflineZipPath
)
$Global:VerbosePreference = "Continue"
$Global:ErrorActionPreference = 'Stop'
$Global:ProgressPreference = 'SilentlyContinue'
try {Stop-Transcript | Out-Null} catch {}
$scriptStep = ""
### DOWNLOADER FUNCTION #####################################################################################################################################
#############################################################################################################################################################
function DownloadWithRetry([string] $downloadURI, [string] $downloadLocation, [int] $retries) {
while ($true) {
try {
(New-Object System.Net.WebClient).DownloadFile($downloadURI, $downloadLocation)
break
}
catch {
$exceptionMessage = $_.Exception.Message
Write-CustomVerbose -Message "Failed to download '$downloadURI': $exceptionMessage"
if ($retries -gt 0) {
$retries--
Write-CustomVerbose -Message "Waiting 10 seconds before retrying. Retries left: $retries"
Start-Sleep -Seconds 10
}
else {
$exception = $_.Exception
throw $exception
}
}
}
}
### CUSTOM VERBOSE FUNCTION #################################################################################################################################
#############################################################################################################################################################
function Write-CustomVerbose {
[cmdletbinding()]
param
(
[parameter(Mandatory = $true)]
[string]$Message = ''
)
begin {}
process {
$verboseTime = (Get-Date).ToShortTimeString()
# Function for displaying formatted log messages. Also displays time in minutes since the script was started
Write-Verbose -Message "[$verboseTime]::[$scriptStep]:: $Message"
}
end {}
}
### OFFLINE AZPKG FUNCTION ##################################################################################################################################
#############################################################################################################################################################
function Add-OfflineAZPKG {
[cmdletbinding()]
param
(
[parameter(Mandatory = $true)]
[string]$azpkgPackageName
)
begin {}
process {
#### Need to upload to blob storage first from extracted ZIP ####
$azpkgFullPath = $null
$azpkgFileName = $null
$azpkgFullPath = Get-ChildItem -Path "$ASDKpath\packages" -Recurse -Include *$azpkgPackageName*.azpkg | ForEach-Object { $_.FullName }
$azpkgFileName = Get-ChildItem -Path "$ASDKpath\packages" -Recurse -Include *$azpkgPackageName*.azpkg | ForEach-Object { $_.Name }
# Check there's not a gallery item already uploaded to storage
if ($(Get-AzureStorageBlob -Container $asdkImagesContainerName -Blob $azpkgFileName -Context $asdkStorageAccount.Context -ErrorAction SilentlyContinue)) {
Write-CustomVerbose -Message "You already have an upload of $azpkgFileName within your Storage Account. No need to re-upload."
Write-CustomVerbose -Message "Gallery path = $((Get-AzureStorageBlob -Container $asdkImagesContainerName -Blob $azpkgFileName -Context $asdkStorageAccount.Context -ErrorAction SilentlyContinue).ICloudBlob.StorageUri.PrimaryUri.AbsoluteUri)"
}
else {
$uploadAzpkgAttempt = 1
while (!$(Get-AzureStorageBlob -Container $asdkImagesContainerName -Blob $azpkgFileName -Context $asdkStorageAccount.Context -ErrorAction SilentlyContinue) -and ($uploadAzpkgAttempt -le 3)) {
try {
# Log back into Azure Stack to ensure login hasn't timed out
Write-CustomVerbose -Message "No existing gallery item found. Upload Attempt: $uploadAzpkgAttempt"
Login-AzureRmAccount -EnvironmentName "AzureStackAdmin" -TenantId $TenantID -Credential $asdkCreds -ErrorAction Stop | Out-Null
Set-AzureStorageBlobContent -File "$azpkgFullPath" -Container $asdkImagesContainerName -Blob "$azpkgFileName" -Context $asdkStorageAccount.Context -ErrorAction Stop | Out-Null
}
catch {
Write-CustomVerbose -Message "Upload failed."
Write-CustomVerbose -Message "$_.Exception.Message"
$uploadAzpkgAttempt++
}
}
}
$azpkgURI = '{0}{1}/{2}' -f $asdkStorageAccount.PrimaryEndpoints.Blob.AbsoluteUri, $asdkImagesContainerName, $azpkgFileName
Write-CustomVerbose -Message "Uploading $azpkgFileName from $azpkgURI"
return [string]$azpkgURI
}
end {}
}
### VALIDATION ##############################################################################################################################################
#############################################################################################################################################################
$scriptStep = "VALIDATION"
Write-CustomVerbose -Message "Validating if running under Admin Privileges"
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (!($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))) {
Write-CustomVerbose -Message "User is not administrator - please ensure you're running as Administrator (right-click, Run as administrator)"
exit
}
### GET START TIME ###
$startTime = Get-Date -Format g
$sw = [Diagnostics.Stopwatch]::StartNew()
### SET LOCATION ###
$ScriptLocation = Get-Location
### SET ERCS IP Address - same for all default ASDKs ###
$ERCSip = "AzS-ERCS01"
# Define Regex for Password Complexity - needs to be at least 12 characters, with at least 1 upper case, 1 lower case, 1 number and 1 special character
$regex = @"
(?=^.{12,123}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*
"@
$emailRegex = @"
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
"@
### SET LOG LOCATION ###
$logDate = Get-Date -Format FileDate
New-Item -ItemType Directory -Path "$ScriptLocation\Logs\$logDate\" -Force | Out-Null
$logPath = "$ScriptLocation\Logs\$logDate"
Write-CustomVerbose -Message "Log folder full path is $logPath"
### START LOGGING ###
$runTime = $(Get-Date).ToString("MMdd-HHmmss")
$fullLogPath = "$logPath\ConfigASDKLog$runTime.txt"
$logStart = Start-Transcript -Path "$fullLogPath" -Append
Write-CustomVerbose -Message $logStart
### INTERNET CONNECTION TEST #################################################################################################################################
##############################################################################################################################################################
try {
Write-CustomVerbose -Message "Testing internet connectivity to various internet resources:"
$azureNetTest = Test-NetConnection portal.azure.com -CommonTCPPort HTTP -InformationLevel Quiet
$gitHubNetTest = Test-NetConnection github.com -CommonTCPPort HTTP -InformationLevel Quiet
$ubuntuNetTest = Test-NetConnection cloud-images.ubuntu.com -CommonTCPPort HTTP -InformationLevel Quiet
$catalogNetTest = Test-NetConnection www.catalog.update.microsoft.com -CommonTCPPort HTTP -InformationLevel Quiet
$microsoftNetTest = Test-NetConnection microsoft.com -CommonTCPPort HTTP -InformationLevel Quiet
$chocolateyNetTest = Test-NetConnection chocolatey.org -CommonTCPPort HTTP -InformationLevel Quiet
Write-CustomVerbose -Message "Connection to Azure: $azureNetTest"
Write-CustomVerbose -Message "Connection to Microsoft.com: $microsoftNetTest"
Write-CustomVerbose -Message "Connection to Microsoft Update Catalog: $catalogNetTest"
Write-CustomVerbose -Message "Connection to GitHub: $gitHubNetTest"
Write-CustomVerbose -Message "Connection to Ubuntu's Image Repo: $ubuntuNetTest"
Write-CustomVerbose -Message "Connection to Chocolatey: $chocolateyNetTest"
if ($azureNetTest -and $gitHubNetTest -and $ubuntuNetTest -and $catalogNetTest -and $microsoftNetTest -and $chocolateyNetTest) {
Write-CustomVerbose -Message "All internet connectivity tests passed"
$validOnlineInstall = $true
}
else {
Write-CustomVerbose -Message "One or more internet connectivity tests failed"
$validOnlineInstall = $false
if ($configAsdkOfflineZipPath) {
Write-CustomVerbose -Message "However, offline zip path has been provided so installation can continue"
if ($registerASDK) {
Write-CustomVerbose -Message "You have selected to register your ASDK, which requires internet connectivity."
}
}
else {
$exception = "No offline zip path provided, and one or more connectivity tests failed. Check your network or provide an offline zip of the dependencies, and try again."
throw $exception
}
}
}
catch {
Write-CustomVerbose -Message "$_.Exception.Message" -ErrorAction Stop
Set-Location $ScriptLocation
return
}
### VALIDATION ###############################################################################################################################################
##############################################################################################################################################################
### Validate parameter combinations to determine deployment type - Online (fully internet connected)
### PartialOnline (internet connected, but using offline zip), and Offline (ADFS with offline zip)
try {
if (($authenticationType.ToString() -like "AzureAd") -and $validOnlineInstall -and !$configAsdkOfflineZipPath) {
$deploymentMode = "Online"
}
elseif (($authenticationType.ToString() -like "AzureAd") -and $validOnlineInstall -and $configAsdkOfflineZipPath) {
$deploymentMode = "PartialOnline"
}
elseif (($authenticationType.ToString() -like "AzureAd") -and !$validOnlineInstall) {
$exception = "Azure AD is the selected authentication model, but you failed internet connectivity tests. Check your internet connectivity, then retry."
throw $exception
}
elseif (($authenticationType.ToString() -like "ADFS") -and $validOnlineInstall -and !$configAsdkOfflineZipPath) {
$deploymentMode = "Online"
}
elseif (($authenticationType.ToString() -like "ADFS") -and $validOnlineInstall -and $configAsdkOfflineZipPath) {
$deploymentMode = "PartialOnline"
}
elseif (($authenticationType.ToString() -like "ADFS") -and !$validOnlineInstall -and $configAsdkOfflineZipPath) {
$deploymentMode = "Offline"
$skipCustomizeHost = $true
}
elseif (($authenticationType.ToString() -like "ADFS") -and !$validOnlineInstall -and !$configAsdkOfflineZipPath) {
$exception = "ADFS is your selected authentication model, but you failed internet connectivity tests and didn't provide an offline zip path."
throw $exception
}
}
catch {
Write-CustomVerbose -Message "$_.Exception.Message" -ErrorAction Stop
Set-Location $ScriptLocation
return
}
### Validate offline Zip Path ###
try {
if ($configAsdkOfflineZipPath) {
Write-CustomVerbose -Message "Validating offline zip path."
$validZipPath = [System.IO.File]::Exists("$configAsdkOfflineZipPath")
$validZipfile = [System.IO.Path]::GetExtension("$configAsdkOfflineZipPath")
if ($validZipPath -eq $true -and $validZipfile -eq ".zip") {
Write-CustomVerbose -Message "Found path to valid zip file"
$configAsdkOfflineZipPath = [System.IO.Path]::GetFullPath($configAsdkOfflineZipPath)
Write-CustomVerbose -Message "The zip path found at $configAsdkOfflineZipPath will be used"
$offlineZipIsValid = $true
}
elseif ($validZipPath -eq $false -or $validZipfile -ne ".zip") {
$configAsdkOfflineZipPath = Read-Host "Zip path is invalid - please enter a valid path to the offline zip file"
$validZipPath = [System.IO.File]::Exists("$configAsdkOfflineZipPath")
$validZipfile = [System.IO.Path]::GetExtension("$configAsdkOfflineZipPath")
if ($validZipPath -eq $false -or $validZipfile -ne ".zip") {
$offlineZipIsValid = $false
Write-CustomVerbose -Message "No valid path to a zip file was entered again. Exiting process..." -ErrorAction Stop
Set-Location $ScriptLocation
return
}
elseif ($validZipPath -eq $true -and $validZipfile -eq ".zip") {
Write-CustomVerbose -Message "Found path to valid zip file"
$configAsdkOfflineZipPath = [System.IO.Path]::GetFullPath($configAsdkOfflineZipPath)
Write-CustomVerbose -Message "The zip file found at $configAsdkOfflineZipPath will be used"
$offlineZipIsValid = $true
}
}
}
### Validate path to ISO File ###
# If both the ConfigASDKfiles.zip file exists AND the $ISOPath has been provided by the user, set the $ISOPath to $null as it will be defined later
if (([System.IO.File]::Exists($configAsdkOfflineZipPath)) -and ([System.IO.File]::Exists($ISOPath))) {
$ISOPath = $null
}
}
catch {
Write-CustomVerbose -Message "$_.Exception.Message" -ErrorAction Stop
Set-Location $ScriptLocation
return
}
### Validate Download Path ###
Write-CustomVerbose -Message "Validating download path."
$validDownloadPath = [System.IO.Directory]::Exists($downloadPath)
If ($validDownloadPath -eq $true) {
Write-CustomVerbose -Message "Download path exists and is valid"
Write-CustomVerbose -Message "Files will be stored at $downloadPath"
$downloadPath = Set-Location -Path "$downloadPath" -PassThru
}
elseif ($validDownloadPath -eq $false) {
$downloadPath = Read-Host "Download path is invalid - please enter a valid path to store your downloads"
$validDownloadPath = [System.IO.Directory]::Exists($downloadPath)
if ($validDownloadPath -eq $false) {
Write-CustomVerbose -Message "No valid folder path was entered again. Exiting process..." -ErrorAction Stop
Set-Location $ScriptLocation
return
}
elseif ($validDownloadPath -eq $true) {
Write-CustomVerbose -Message "Download path exists and is valid"
Write-CustomVerbose -Message "Files will be stored at $downloadPath"
$downloadPath = Set-Location -Path "$downloadPath" -PassThru
}
}
Write-CustomVerbose -Message "Selected identity provider is $authenticationType"
### VALIDATE CREDS ##########################################################################################################################################
#############################################################################################################################################################
### Validate Virtual Machine (To be created) Password ###
if ([string]::IsNullOrEmpty($VMpwd)) {
Write-CustomVerbose -Message "You didn't enter a password for the virtual machines that the ASDK configurator will create."
$secureVMpwd = Read-Host "Please enter a password for the virtual machines that will be created during this process" -AsSecureString -ErrorAction Stop
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureVMpwd)
$VMpwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
}
Write-CustomVerbose -Message "Checking to see if Virtual Machine password is strong..."
if ($VMpwd -cmatch $regex -eq $true) {
Write-CustomVerbose -Message "Virtual Machine password meets desired complexity level"
# Convert plain text password to a secure string
$secureVMpwd = ConvertTo-SecureString -AsPlainText $VMpwd -Force
}
elseif ($VMpwd -cmatch $regex -eq $false) {
Write-CustomVerbose -Message "Virtual Machine password doesn't meet complexity requirements, it needs to be at least 12 characters in length."
Write-CustomVerbose -Message "Your password should also have at least 3 of the following 4 options: 1 upper case, 1 lower case, 1 number, 1 special character."
Write-CustomVerbose -Message 'The App Service installation requires a password of this strength. An Example would be p@ssw0rd123!'
# Obtain new password and store as a secure string
$secureVMpwd = Read-Host -AsSecureString "Enter VM password again"
# Convert to plain text to test regex complexity
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureVMpwd)
$VMpwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
if ($VMpwd -cmatch $regex -eq $true) {
Write-CustomVerbose -Message "Virtual Machine password matches desired complexity"
# Convert plain text password to a secure string
$secureVMpwd = ConvertTo-SecureString -AsPlainText $VMpwd -Force
# Clean up unused variable
Remove-Variable -Name VMpwd -ErrorAction SilentlyContinue
}
else {
Write-CustomVerbose -Message "No valid password was entered again. Exiting process..." -ErrorAction Stop
Set-Location $ScriptLocation
return
}
}
### Validate Azure Stack Development Kit Deployment Credentials ###
if ([string]::IsNullOrEmpty($azureStackAdminPwd)) {
Write-CustomVerbose -Message "You didn't enter the Azure Stack Development Kit Deployment password."
$secureAzureStackAdminPwd = Read-Host "Please enter the password used for the Azure Stack Development Kit Deployment, for account AzureStack\AzureStackAdmin" -AsSecureString -ErrorAction Stop
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureAzureStackAdminPwd)
$azureStackAdminPwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
}
Write-CustomVerbose -Message "Checking to see Azure Stack Admin password is strong..."
$azureStackAdminUsername = "AzureStack\AzureStackAdmin"
if ($azureStackAdminPwd -cmatch $regex -eq $true) {
Write-CustomVerbose -Message "Azure Stack Development Kit Deployment password for AzureStack\AzureStackAdmin, meets desired complexity level"
# Convert plain text password to a secure string
$secureAzureStackAdminPwd = ConvertTo-SecureString -AsPlainText $azureStackAdminPwd -Force
$azureStackAdminCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $azureStackAdminUsername, $secureAzureStackAdminPwd -ErrorAction Stop
}
elseif ($azureStackAdminPwd -cmatch $regex -eq $false) {
Write-Host "`r`nAzure Stack Admin (AzureStack\AzureStackAdmin) password is not a strong password.`nIt should ideally be at least 8 characters, with at least 1 upper case, 1 lower case, and 1 special character.`nPlease consider a stronger password in the future.`r`n" -ForegroundColor Cyan
Start-Sleep -Seconds 10
# Convert plain text password to a secure string
$secureAzureStackAdminPwd = ConvertTo-SecureString -AsPlainText $azureStackAdminPwd -Force
$azureStackAdminCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $azureStackAdminUsername, $secureAzureStackAdminPwd -ErrorAction Stop
}
### Credentials Recap ###
# $azureStackAdminUsername = "AzureStack\AzureStackAdmin" | Used to log into the local ASDK Host
# azureStackAdminPwd (and $secureAzureStackAdminPwd) | Used to log into the local ASDK Host
# $azureStackAdminCreds | Used to log into the local ASDK Host
### Validate Azure Stack Development Kit Service Administrator Credentials (AZURE AD ONLY) ###
if ($authenticationType.ToString() -like "AzureAd") {
### Validate Azure AD Service Administrator Username (Used for ASDK Deployment) ###
if ([string]::IsNullOrEmpty($azureAdUsername)) {
Write-CustomVerbose -Message "You didn't enter a username for the Azure AD login."
$azureAdUsername = Read-Host "Please enter a username in the format username@<directoryname>.onmicrosoft.com, or your own custom domain, for example username@contoso.com" -ErrorAction Stop
}
Write-CustomVerbose -Message "Checking to see if Azure AD Service Administrator (Used for ASDK Deployment) username is correctly formatted..."
if ($azureAdUsername.ToLower() -cmatch $emailRegex -eq $true) {
Write-CustomVerbose -Message "Azure AD Service Administrator username (Used for ASDK Deployment) is correctly formatted."
$azureAdUsername = $azureAdUsername.ToLower()
Write-CustomVerbose -Message "$azureAdUsername will be used to connect to Azure."
}
elseif ($azureAdUsername.ToLower() -cmatch $emailRegex -eq $false) {
Write-CustomVerbose -Message "Azure AD Service Administrator Username (Used for ASDK Deployment) isn't correctly formatted. It should be entered in the format username@<directoryname>.onmicrosoft.com, or your own custom domain, for example username@contoso.com"
# Obtain new username
$azureAdUsername = Read-Host "Enter Azure AD Service Administrator Username (Used for ASDK Deployment) again" -ErrorAction Stop
if ($azureAdUsername.ToLower() -cmatch $emailRegex -eq $true) {
$azureAdUsername = $azureAdUsername.ToLower()
Write-CustomVerbose -Message "Azure AD Service Administrator Username (Used for ASDK Deployment) is correctly formatted."
Write-CustomVerbose -Message "$azureAdUsername will be used to connect to Azure."
}
else {
Write-CustomVerbose -Message "No valid Azure AD Service Administrator Username (Used for ASDK Deployment) was entered again. Exiting process..." -ErrorAction Stop
Set-Location $ScriptLocation
return
}
}
### Validate Azure AD Service Administrator (Used for ASDK Deployment) Password ###
if ([string]::IsNullOrEmpty($azureAdPwd)) {
Write-CustomVerbose -Message "You didn't enter the Azure AD Service Administrator account (Used for ASDK Deployment) password."
$secureAzureAdPwd = Read-Host "Please enter the password for the Azure AD Service Administrator account used to deploy the ASDK. It should be at least 8 characters, with at least 1 upper case and 1 special character." -AsSecureString -ErrorAction Stop
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureAzureAdPwd)
$azureAdPwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
}
Write-CustomVerbose -Message "Checking to see if password for the Azure AD Service Administrator used to deploy the ASDK, is strong..."
if ($azureAdPwd -cmatch $regex -eq $true) {
Write-CustomVerbose -Message "Password for the Azure AD Service Administrator account used to deploy the ASDK meets desired complexity level"
# Convert plain text password to a secure string
$secureAzureAdPwd = ConvertTo-SecureString -AsPlainText $azureAdPwd -Force
$azureAdCreds = New-Object -TypeName System.Management.Automation.PSCredential ($azureAdUsername, $secureAzureAdPwd) -ErrorAction Stop
}
elseif ($azureAdPwd -cmatch $regex -eq $false) {
Write-Host "`r`nAzure AD Service Administrator account password is not a strong password.`nIt should ideally be at least 8 characters, with at least 1 upper case, 1 lower case, and 1 special character.`nPlease consider a stronger password in the future.`r`n" -ForegroundColor Cyan
Start-Sleep -Seconds 10
$secureAzureAdPwd = ConvertTo-SecureString -AsPlainText $azureAdPwd -Force
$azureAdCreds = New-Object -TypeName System.Management.Automation.PSCredential ($azureAdUsername, $secureAzureAdPwd) -ErrorAction Stop
}
$asdkCreds = $azureAdCreds
### Credentials Recap ###
# $azureAdUsername | Used for Azure AD athentication to log into Azure/Azure Stack portals
# $azureAdPwd (and $secureAzureAdPwd) | Used to log into Azure/Azure Stack portals
# $azureAdCreds | Combined credentials, used to log into Azure/Azure Stack portals
# $asdkCreds | New variable to represent the $azureAdCreds (if Azure AD) or the $azureStackAdminCreds (if ADFS)
if ($useAzureCredsForRegistration -and $registerASDK) {
$azureRegCreds = $azureAdCreds
}
elseif (!$useAzureCredsForRegistration -and $registerASDK) {
if ([string]::IsNullOrEmpty($azureRegUsername)) {
Write-CustomVerbose -Message "You didn't enter a username for Azure account you'll use to register the Azure Stack to."
$azureRegUsername = Read-Host "Please enter a username in the format username@<directoryname>.onmicrosoft.com, or your own custom domain, for example username@contoso.com" -ErrorAction Stop
}
Write-CustomVerbose -Message "Checking to see if the Azure AD username is correctly formatted..."
if ($azureRegUsername -cmatch $emailRegex -eq $true) {
Write-CustomVerbose -Message "Azure AD username is correctly formatted."
Write-CustomVerbose -Message "$azureRegUsername will be used to connect to Azure."
}
elseif ($azureRegUsername -cmatch $emailRegex -eq $false) {
Write-CustomVerbose -Message "Azure AD username isn't correctly formatted. It should be entered in the format username@<directoryname>.onmicrosoft.com, or your own custom domain, for example username@contoso.com"
# Obtain new username
$azureRegUsername = Read-Host "Enter Azure AD username again"
if ($azureRegUsername -cmatch $emailRegex -eq $true) {
Write-CustomVerbose -Message "Azure AD username is correctly formatted."
Write-CustomVerbose -Message "$azureRegUsername will be used to connect to Azure."
}
else {
Write-CustomVerbose -Message "No valid Azure AD username was entered again. Exiting process..." -ErrorAction Stop
Set-Location $ScriptLocation
return
}
}
### Validate Azure AD Registration Password ###
if ([string]::IsNullOrEmpty($azureRegPwd)) {
Write-CustomVerbose -Message "You didn't enter the Azure AD password that you want to use for registration."
$secureAzureRegPwd = Read-Host "Please enter the Azure AD password you wish to use for registration. It should ideally be at least 8 characters, with at least 1 upper case and 1 special character." -AsSecureString -ErrorAction Stop
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureAzureRegPwd)
$azureRegPwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
}
Write-CustomVerbose -Message "Checking to see if Azure AD password is strong..."
if ($azureRegPwd -cmatch $regex -eq $true) {
Write-CustomVerbose -Message "Azure AD password meets desired complexity level"
# Convert plain text password to a secure string
$secureAzureRegPwd = ConvertTo-SecureString -AsPlainText $azureRegPwd -Force
$azureRegCreds = New-Object -TypeName System.Management.Automation.PSCredential ($azureRegUsername, $secureAzureRegPwd) -ErrorAction Stop
}
elseif ($azureRegPwd -cmatch $regex -eq $false) {
Write-Host "`r`nAzure AD password for registration is not a strong password.`nIt should ideally be at least 8 characters, with at least 1 upper case, 1 lower case, and 1 special character.`nPlease consider a stronger password in the future.`r`n" -ForegroundColor Cyan
Start-Sleep -Seconds 10
$secureAzureRegPwd = ConvertTo-SecureString -AsPlainText $azureRegPwd -Force
$azureRegCreds = New-Object -TypeName System.Management.Automation.PSCredential ($azureRegUsername, $secureAzureRegPwd) -ErrorAction Stop
}
}
}
### Create Cloud Admin Creds ###
$cloudAdminUsername = "azurestack\cloudadmin"
$cloudAdminCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $cloudAdminUsername, $secureAzureStackAdminPwd -ErrorAction Stop
### Credentials Recap ###
# $azureRegUsername | Used for Azure AD authentication to register the ASDK if NOT using same Azure AD Creds as deployment
# $azureRegPwd (and $secureAzureRegPwd) | Used for Azure AD authentication to register the ASDK if NOT using same Azure AD Creds as deployment
# $azureRegCreds | Combined credentials, used for Azure AD authentication to register the ASDK if NOT using same Azure AD Creds as deployment
# $cloudAdminCreds | Used for ADFS login (azurestackadmin not used) and also MySQL/SQL RP deployment
if ($authenticationType.ToString() -like "ADFS") {
$asdkCreds = $cloudAdminCreds
}
### Credentials Recap ###
# $asdkCreds | If deployment is using ADFS, $asdkCreds will be set to match $azureStackAdminCreds, which should be azurestack\azurestackadmin and accompanying password
if ($authenticationType.ToString() -like "ADFS" -and $registerASDK) {
# If the user has chosen ADFS authentication, they will need to be prompted to provide some additional Azure credentials to register the ASDK.
# This If statement captures those credentials
Remove-Variable -Name azureAdPwd -Force -ErrorAction SilentlyContinue
Remove-Variable -Name azureAdUsername -Force -ErrorAction SilentlyContinue
Write-CustomVerbose -Message "Checking for an Azure AD username - this account will be used to register the ADFS-based ASDK to Azure..."
if ([string]::IsNullOrEmpty($azureRegUsername)) {
Write-CustomVerbose -Message "You didn't enter a username for Azure account you'll use to register the Azure Stack to."
$azureRegUsername = Read-Host "Please enter a username in the format username@<directoryname>.onmicrosoft.com, or your own custom domain, for example username@contoso.com" -ErrorAction Stop
}
else {
Write-CustomVerbose -Message "Found an Azure AD username that will be used for registering this ADFS-based Azure Stack to Azure"
Write-CustomVerbose -Message "Account username is $azureRegUsername"
}
Write-CustomVerbose -Message "Checking to see if the Azure AD username, that will be used for Azure Stack registration to Azure, is correctly formatted..."
if ($azureRegUsername -cmatch $emailRegex -eq $true) {
Write-CustomVerbose -Message "Azure AD username is correctly formatted."
Write-CustomVerbose -Message "$azureRegUsername will be used to register this ADFS-based Azure Stack to Azure."
}
elseif ($azureRegUsername -cmatch $emailRegex -eq $false) {
Write-CustomVerbose -Message "Azure AD username isn't correctly formatted. It should be entered in the format username@<directoryname>.onmicrosoft.com, or your own custom domain, for example username@contoso.com"
# Obtain new username
$azureRegUsername = Read-Host "Enter Azure AD username again"
if ($azureRegUsername -cmatch $emailRegex -eq $true) {
Write-CustomVerbose -Message "Azure AD username is correctly formatted."
Write-CustomVerbose -Message "$azureRegUsername will be used to register this ADFS-based Azure Stack to Azure."
}
else {
Write-CustomVerbose -Message "No valid Azure AD username was entered again. Exiting process..." -ErrorAction Stop
Set-Location $ScriptLocation
return
}
}
### Validate Azure AD Registration Password ADFS-based Azure Stack ###
Write-CustomVerbose -Message "Checking for an Azure AD password - this account will be used to register the ADFS-based ASDK to Azure..."
if ([string]::IsNullOrEmpty($azureRegPwd)) {
Write-CustomVerbose -Message "You didn't enter the Azure AD password that you want to use for registration."
$secureAzureRegPwd = Read-Host "Please enter the Azure AD password you wish to use for registration. It should ideally be at least 8 characters, with at least 1 upper case and 1 special character." -AsSecureString -ErrorAction Stop
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureAzureRegPwd)
$azureRegPwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
}
Write-CustomVerbose -Message "Checking to see if Azure AD password for registration is strong..."
if ($azureRegPwd -cmatch $regex -eq $true) {
Write-CustomVerbose -Message "Azure AD password meets desired complexity level"
# Convert plain text password to a secure string
$secureAzureRegPwd = ConvertTo-SecureString -AsPlainText $azureRegPwd -Force
$azureRegCreds = New-Object -TypeName System.Management.Automation.PSCredential ($azureRegUsername, $secureAzureRegPwd) -ErrorAction Stop
}
elseif ($azureRegPwd -cmatch $regex -eq $false) {
Write-Host "`r`nAzure AD password for registration is not a strong password.`nIt should ideally be at least 8 characters, with at least 1 upper case, 1 lower case, and 1 special character.`nPlease consider a stronger password in the future.`r`n" -ForegroundColor Cyan
Start-Sleep -Seconds 10
$secureAzureRegPwd = ConvertTo-SecureString -AsPlainText $azureRegPwd -Force
$azureRegCreds = New-Object -TypeName System.Management.Automation.PSCredential ($azureRegUsername, $secureAzureRegPwd) -ErrorAction Stop
}
}
if ($registerASDK) {
Write-CustomVerbose -Message "Checking for a valid Azure subscription ID that will be used to register the Azure Stack to Azure"
### Validate Azure Subscription ID for Registration ###
if ([string]::IsNullOrEmpty($azureRegSubId)) {
Write-CustomVerbose -Message "You didn't enter a subscription ID for registering your Azure Stack in Azure."
$azureRegSubId = Read-Host "Please enter a valid Azure subscription ID" -ErrorAction Stop
}
if ($azureRegSubId) {
Write-CustomVerbose -Message "Azure subscription ID has been provided."
Write-CustomVerbose -Message "$azureRegSubId will be used to register this Azure Stack with Azure."
}
elseif ([string]::IsNullOrEmpty($azureRegSubId)) {
Write-CustomVerbose -Message "No valid Azure subscription ID was entered again. Exiting process..." -ErrorAction Stop
Set-Location $ScriptLocation
return
}
}
### CREATE CSV ##############################################################################################################################################
#############################################################################################################################################################
### Check if ConfigASDKProgressLog.csv exists ###
$ConfigASDKProgressLogPath = "$downloadPath\ConfigASDKProgressLog.csv"
$validConfigASDKProgressLogPath = [System.IO.File]::Exists($ConfigASDKProgressLogPath)
If ($validConfigASDKProgressLogPath -eq $true) {
Write-CustomVerbose -Message "ConfigASDkProgressLog.csv exists - this must be a rerun"
Write-CustomVerbose -Message "Starting from previous failed step`r`n"
$isRerun = $true
$progress = Import-Csv $ConfigASDKProgressLogPath
Write-Output $progress | Out-Host
}
elseif ($validConfigASDKProgressLogPath -eq $false) {
Write-CustomVerbose -Message "No ConfigASDkProgressLog.csv exists - this must be a fresh deployment"
Write-CustomVerbose -Message "Creating ConfigASDKProgressLog.csv`r`n"
Add-Content -Path $ConfigASDKProgressLogPath -Value '"Stage","Status"' -Force -Confirm:$false
$ConfigASDKprogress = @(
'"ExtractZip","Incomplete"'
'"InstallPowerShell","Incomplete"'
'"DownloadTools","Incomplete"'
'"HostConfiguration","Incomplete"'
'"Registration","Incomplete"'
'"UbuntuImage","Incomplete"'
'"WindowsImage","Incomplete"'
'"MySQLGalleryItem","Incomplete"'
'"SQLServerGalleryItem","Incomplete"'
'"VMExtensions","Incomplete"'
'"MySQLRP","Incomplete"'
'"SQLServerRP","Incomplete"'
'"MySQLSKUQuota","Incomplete"'
'"SQLServerSKUQuota","Incomplete"'
'"UploadScripts","Incomplete"'
'"MySQLDBVM","Incomplete"'
'"SQLServerDBVM","Incomplete"'
'"MySQLAddHosting","Incomplete"'
'"SQLServerAddHosting","Incomplete"'
'"AppServiceFileServer","Incomplete"'
'"AppServiceSQLServer","Incomplete"'
'"DownloadAppService","Incomplete"'
'"GenerateAppServiceCerts","Incomplete"'
'"CreateServicePrincipal","Incomplete"'
'"GrantAzureADAppPermissions","Incomplete"'
'"InstallAppService","Incomplete"'
'"RegisterNewRPs","Incomplete"'
'"CreatePlansOffers","Incomplete"'
'"InstallHostApps","Incomplete"'
'"CreateOutput","Incomplete"'
)
$ConfigASDKprogress | ForEach-Object { Add-Content -Path $ConfigASDKProgressLogPath -Value $_ }
$progress = Import-Csv -Path $ConfigASDKProgressLogPath
Write-Output $progress | Out-Host
}
### CREATE ASDK FOLDER ######################################################################################################################################
#############################################################################################################################################################
### CREATE ASDK FOLDER ###
$ASDKpath = [System.IO.Directory]::Exists("$downloadPath\ASDK")
if ($ASDKpath -eq $true) {
$ASDKpath = "$downloadPath\ASDK"
Write-CustomVerbose -Message "ASDK folder exists at $downloadPath - no need to create it."
Write-CustomVerbose -Message "Download files will be placed in $downloadPath\ASDK"
Write-CustomVerbose -Message "ASDK folder full path is $ASDKpath"
if (!$isRerun) {
# If this is a fresh run, the $asdkPath should be empty to avoid any conflicts.
# It may exist from a previous successful run
Write-CustomVerbose -Message "Cleaning up an old ASDK Folder from a previous completed run"
# Will attempt multiple times as sometimes it fails
$i = 0
While ($i -le 3) {
Remove-Item "$ASDKpath\*" -Force -Recurse -Confirm:$false -ErrorAction SilentlyContinue -Verbose
$i++
}
}
}
elseif ($ASDKpath -eq $false) {
# Create the ASDK folder.
Write-CustomVerbose -Message "ASDK folder doesn't exist within $downloadPath, creating it"
mkdir "$downloadPath\ASDK" -Force | Out-Null
$ASDKpath = "$downloadPath\ASDK"
Write-CustomVerbose -Message "ASDK folder full path is $ASDKpath"
}
### EXTRACT ZIP (OPTIONAL) ##################################################################################################################################
#############################################################################################################################################################
$progress = Import-Csv -Path $ConfigASDKProgressLogPath
$RowIndex = [array]::IndexOf($progress.Stage, "ExtractZip")
$scriptStep = $($progress[$RowIndex].Stage).ToString().ToUpper()
if (($configAsdkOfflineZipPath) -and ($offlineZipIsValid = $true)) {
if (($progress[$RowIndex].Status -eq "Incomplete") -or ($progress[$RowIndex].Status -eq "Failed")) {
try {
Write-CustomVerbose -Message "ASDK Configurator dependency files located at: $validZipPath"
Write-CustomVerbose -Message "Starting extraction to $downloadPath"
### Extract the Zip file, move contents to appropriate place
Expand-Archive -Path $configAsdkOfflineZipPath -DestinationPath $downloadPath -Force -Verbose -ErrorAction Stop
# Update the ConfigASDKProgressLog.csv file with successful completion
Write-CustomVerbose -Message "Updating ConfigASDKProgressLog.csv file with successful completion`r`n"
$progress[$RowIndex].Status = "Complete"
$progress | Export-Csv $ConfigASDKProgressLogPath -NoTypeInformation -Force
Write-Output $progress | Out-Host
}
catch {
Write-CustomVerbose -Message "ASDK Configuration Stage: $($progress[$RowIndex].Stage) Failed`r`n"
$progress[$RowIndex].Status = "Failed"
$progress | Export-Csv $ConfigASDKProgressLogPath -NoTypeInformation -Force
Write-Output $progress | Out-Host
Write-CustomVerbose -Message "$_.Exception.Message" -ErrorAction Stop
Set-Location $ScriptLocation
return
}
}
elseif ($progress[$RowIndex].Status -eq "Complete") {
Write-CustomVerbose -Message "ASDK Configuration Stage: $($progress[$RowIndex].Stage) previously completed successfully"
}
}
elseif (!$configAsdkOfflineZipPath) {
Write-CustomVerbose -Message "Skipping zip extraction - this is a 100% online deployment`r`n"
# Update the ConfigASDKProgressLog.csv file with successful completion
$progress[$RowIndex].Status = "Skipped"
$progress | Export-Csv $ConfigASDKProgressLogPath -NoTypeInformation -Force
Write-Output $progress | Out-Host
}
### VALIDATE ISO ############################################################################################################################################
#############################################################################################################################################################
$scriptStep = "VALIDATE ISO"
try {
Write-CustomVerbose -Message "Validating ISO path"
# If this deployment is PartialOnline/Offline and using the Zip, we need to search for the ISO
if (($configAsdkOfflineZipPath) -and ($offlineZipIsValid = $true)) {
$ISOPath = Get-ChildItem -Path "$downloadPath\*" -Recurse -Include *.iso -ErrorAction Stop | ForEach-Object { $_.FullName }
}
$validISOPath = [System.IO.File]::Exists($ISOPath)
$validISOfile = [System.IO.Path]::GetExtension("$ISOPath")
if ($validISOPath -eq $true -and $validISOfile -eq ".iso") {
Write-CustomVerbose -Message "Found path to valid ISO file"
$ISOPath = [System.IO.Path]::GetFullPath($ISOPath)
Write-CustomVerbose -Message "The Windows Server 2016 Eval found at $ISOPath will be used"
}
elseif ($validISOPath -eq $false -or $validISOfile -ne ".iso") {
$ISOPath = Read-Host "ISO path is invalid - please enter a valid path to the Windows Server 2016 ISO"
$validISOPath = [System.IO.File]::Exists($ISOPath)
$validISOfile = [System.IO.Path]::GetExtension("$ISOPath")
if ($validISOPath -eq $false -or $validISOfile -ne ".iso") {
Write-CustomVerbose -Message "No valid path to a Windows Server 2016 ISO was entered again. Exiting process..." -ErrorAction Stop
Set-Location $ScriptLocation
return
}
elseif ($validISOPath -eq $true -and $validISOfile -eq ".iso") {
Write-CustomVerbose -Message "Found path to valid ISO file"
$ISOPath = [System.IO.Path]::GetFullPath($ISOPath)
Write-CustomVerbose -Message "The Windows Server 2016 Eval found at $ISOPath will be used"
}
}
}
catch {
Write-CustomVerbose -Message "$_.Exception.Message" -ErrorAction Stop
Set-Location $ScriptLocation
return
}
### INSTALL POWERSHELL ######################################################################################################################################
#############################################################################################################################################################
$progress = Import-Csv -Path $ConfigASDKProgressLogPath
$RowIndex = [array]::IndexOf($progress.Stage, "InstallPowerShell")
$scriptStep = $($progress[$RowIndex].Stage).ToString().ToUpper()
if (($progress[$RowIndex].Status -eq "Incomplete") -or ($progress[$RowIndex].Status -eq "Failed")) {
try {
Import-Module -Name PowerShellGet -ErrorAction Stop
Import-Module -Name PackageManagement -ErrorAction Stop
Write-CustomVerbose -Message "Uninstalling previously existing Azure Stack modules"
Uninstall-Module AzureRM.AzureStackAdmin -Force -ErrorAction SilentlyContinue
Uninstall-Module AzureRM.AzureStackStorage -Force -ErrorAction SilentlyContinue
Uninstall-Module -Name AzureStack -Force -ErrorAction SilentlyContinue
Get-Module Azs.* -ListAvailable | Uninstall-Module -Force -ErrorAction SilentlyContinue
if ($deploymentMode -eq "Online") {
# If this is an online deployment, pull down the PowerShell modules from the Internet
Write-CustomVerbose -Message "Configuring the PSGallery Repo for Azure Stack PowerShell Modules"
Unregister-PSRepository -Name PSGallery -ErrorAction SilentlyContinue
Register-PsRepository -Default
Get-PSRepository -Name "PSGallery"
Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
Get-PSRepository -Name "PSGallery"
Install-Module -Name AzureRm.BootStrapper -Force -ErrorAction Stop
Use-AzureRmProfile -Profile 2017-03-09-profile -Force -ErrorAction Stop
Install-Module -Name AzureStack -RequiredVersion 1.4.0 -Force -ErrorAction Stop
}
elseif (($deploymentMode -eq "PartialOnline") -or ($deploymentMode -eq "Offline")) {
# If this is a PartialOnline or Offline deployment, pull from the extracted zip file
$SourceLocation = "$downloadPath\ASDK\PowerShell"
$RepoName = "MyNuGetSource"
Register-PSRepository -Name $RepoName -SourceLocation $SourceLocation -InstallationPolicy Trusted
Install-Module AzureRM -Repository $RepoName -Force -ErrorAction Stop
Install-Module AzureStack -Repository $RepoName -Force -ErrorAction Stop
}
# Update the ConfigASDKProgressLog.csv file with successful completion
Write-CustomVerbose -Message "Updating ConfigASDKProgressLog.csv file with successful completion`r`n"
$progress[$RowIndex].Status = "Complete"
$progress | Export-Csv $ConfigASDKProgressLogPath -NoTypeInformation -Force
Write-Output $progress | Out-Host
}
catch {
Write-CustomVerbose -Message "ASDK Configuration Stage: $($progress[$RowIndex].Stage) Failed`r`n"
$progress[$RowIndex].Status = "Failed"
$progress | Export-Csv $ConfigASDKProgressLogPath -NoTypeInformation -Force
Write-Output $progress | Out-Host
Write-CustomVerbose -Message "$_.Exception.Message" -ErrorAction Stop
Set-Location $ScriptLocation
return
}
}
elseif ($progress[$RowIndex].Status -eq "Complete") {
Write-CustomVerbose -Message "ASDK Configuration Stage: $($progress[$RowIndex].Stage) previously completed successfully"
}
### TEST ALL LOGINS #########################################################################################################################################
#############################################################################################################################################################
$scriptStep = "TEST LOGINS"
# Clear all logins
Get-AzureRmContext -ListAvailable | Where-Object {$_.Environment -like "Azure*"} | Remove-AzureRmAccount | Out-Null
Clear-AzureRmContext -Scope CurrentUser -Force
# Register an AzureRM environment that targets your administrative Azure Stack instance
Write-CustomVerbose -Message "ASDK Configurator will now test all logins"
$ArmEndpoint = "https://adminmanagement.local.azurestack.external"
Add-AzureRMEnvironment -Name "AzureStackAdmin" -ArmEndpoint "$ArmEndpoint" -ErrorAction Stop
$ADauth = (Get-AzureRmEnvironment -Name "AzureStackAdmin").ActiveDirectoryAuthority
if ($authenticationType.ToString() -like "AzureAd") {
try {
### TEST AZURE LOGIN - Login to Azure Cloud (used for App Service App creation)
Write-CustomVerbose -Message "Testing Azure login with Azure Active Directory`r`n"
Login-AzureRmAccount -EnvironmentName "AzureCloud" -TenantId "$azureDirectoryTenantName" -Credential $asdkCreds -ErrorAction Stop | Out-Null