This repository has been archived by the owner on Oct 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 84
/
build.ps1
3059 lines (2770 loc) · 144 KB
/
build.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Builds an Azure IoT Connected factory solution preconfigured solution (CF PCS).
.DESCRIPTION
This script allows to build all components of the CF PCS. It is able to create and delete all required Azure resources and deploy the
different components to the Azure cloud resources.
.PARAMETER Command
The command to execute. Supported commands are: "build", "updatesimulation", "local", "cloud", "clean", "delete"
build: Does build the simulation.
.PARAMETER Configuration
The configuration to build.or deploy. Supported values are: "debug", "release"
.PARAMETER DeploymentName
The name of your solution deployment. The name must match the following regex: "^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{3,49}[a-zA-Z0-9]{1,1}$"
.PARAMETER AzureEnvironmentName
The name of the Azure environment to deploy your solution to. Supported values are: "AzureCloud"
.PARAMETER LowCost
Use low cost SKUs of the required Azure resources.
.PARAMETER Force
Enforced deployment even there is already a deployment with the same name.
.PARAMETER PresetAzureAccountName
The name of the user account to use. This prevents from entering the selection menu if the account is valid.
.PARAMETER PresetAzureSubscriptionName
The name of the Azure subscription to use. This prevents from entering the selection menu if the subscription name is valid.
.PARAMETER PresetAzureLocationName
The name of the Azure location to use. This prevents from entering the selection menu if the location name is valid.
.PARAMETER PresetAzureDirectoryName
The name of the Azure directory to use. This prevents from entering the selection menu if the directory name is valid.
.PARAMETER VmAdminPassword
The admin password of the VM used for the simulation.
.EXAMPLE
./build.ps1
Builds the solution.
.EXAMPLE
./build.ps1 build
Builds the solution.
.EXAMPLE
./build.ps1 clean
Removes all build artifacts and build output.
.EXAMPLE
./build.ps1 local
Allocates all cloud resources, but not deploy your solution to the cloud.
This is to develop and test your solution locally.
.EXAMPLE
./build.ps1 cloud -Configuration release -DeploymentName mydeployment
Build the release version of your solution and deploys it to the AzureCloud environment.
.EXAMPLE
./build.ps1 cloud -Configuration release -DeploymentName mydeployment
Build the release version of your solution and deploys it to the AzureCloud environment.
.EXAMPLE
./build.ps1 cloud -Configuration release -DeploymentName mydeployment -LowCost
Build the release version of your solution and deploys it to the AzureCloud environment. The deployment is using those SKUs of the required resources which generate lowest cost.
.EXAMPLE
./build.ps1 cloud -Configuration release -DeploymentName mydeployment -PresetAzureAccountName [email protected] -PresetAzureSubscriptionName myszuresubscription -PresetAzureLocationName "West Europe" -PresetAzureDirectoryName mydomain.com
Build the release version of your solution and deploys it to the AzureCloud environment using the preset values. This allows you to run the script without
selecting any values manually.
.EXAMPLE
./build.ps1 cloud -Configuration release -DeploymentName mydeployment -AzureEnvironmentname AzureGermanCloud
Build the release version of your solution and deploys it to the AzureGermanCloud environment.
.EXAMPLE
./build.ps1 updatesimulation -DeploymentName mydeployment
Updates the simulation in the VM of the resource group mydeployment.
.EXAMPLE
./build.ps1 delete -DeploymentName mydeployment
Updates the web packages of the resource group mydeployment.
.NOTES
This is the user deployment script of Azure IoT Suite Connected factory.
#>
[CmdletBinding()]
Param(
[Parameter(Position=0, Mandatory=$false, HelpMessage="Specify the command to execute.")]
[ValidateSet("build", "updatesimulation", "local", "cloud", "clean", "delete")]
[string] $Command = "build",
[Parameter(Mandatory=$false, HelpMessage="Specify the configuration to build.")]
[ValidateSet("debug", "release")]
[string] $Configuration = "debug",
[Parameter(Mandatory=$false, HelpMessage="Specify the name of the solution")]
[ValidatePattern("^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{3,49}[a-zA-Z0-9]{1,1}$")]
[ValidateLength(3, 62)]
[string] $DeploymentName = "local",
[Parameter(Mandatory=$false, HelpMessage="Specify the name of the Azure environment to deploy your solution into.")]
[ValidateSet("AzureCloud")]
[string] $AzureEnvironmentName = "AzureCloud",
[Parameter(Mandatory=$false, HelpMessage="Specify a username to use for the Azure deployment.")]
[switch] $LowCost = $false,
[Parameter(Mandatory=$false, HelpMessage="Enforce redeployment.")]
[switch] $Force = $false,
[Parameter(Mandatory=$false, HelpMessage="Flag to use SKUs with lowest cost for all required resources.")]
[string] $PresetAzureAccountName,
[Parameter(Mandatory=$false, HelpMessage="Specify the Azure subscription to use for the Azure deployment.")]
[string] $PresetAzureSubscriptionName,
[Parameter(Mandatory=$false, HelpMessage="Specify the Azure location to use for the Azure deployment.")]
[string] $PresetAzureLocationName,
[Parameter(Mandatory=$false, HelpMessage="Specify the Azure AD name to use for the Azure deployment.")]
[string] $PresetAzureDirectoryName,
[Parameter(Mandatory=$false, HelpMessage="Specify the admin password to use for the simulation VM.")]
[string] $VmAdminPassword
)
Function CheckCommandAvailability()
{
Param(
[Parameter(Mandatory=$true,Position=0)] $command
)
try
{
Get-Command -Name "$command" -ErrorAction SilentlyContinue
}
catch
{
Write-Error ("$(Get-Date –f $TIME_STAMP_FORMAT) - '{0}' not found. Is your path variable set correct or the PowerShell module implementing the cmdlet installed?" -f $command)
throw ("'{0}' not found. Is your path variable set correct or the PowerShell module implementing the cmdlet installed?" -f $command)
}
return $true
}
function InstallNuget()
{
$nugetPath = "{0}/.nuget" -f $script:IoTSuiteRootPath
if (-not (Test-Path "$nugetPath"))
{
New-Item -Path "$nugetPath" -ItemType "Directory" | Out-Null
}
if (-not (Test-Path "$nugetPath/nuget.exe"))
{
$sourceNugetExe = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
$targetFile = $nugetPath + "/nuget.exe"
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - 'nuget.exe' not found. Downloading latest from $sourceNugetExe ...")
Invoke-WebRequest $sourceNugetExe -OutFile "$targetFile"
}
}
Function CheckModuleVersion()
{
Param(
[Parameter(Mandatory=$True,Position=0)] $ModuleName,
[Parameter(Mandatory=$True,Position=1)] $ExpectedVersion
)
Import-Module $ModuleName 4> $null
$Module = Get-Module -Name $ModuleName
if ($Module.Count -eq 0)
{
# If the script fails here, you need to Install-Module from the PSGallery in an Administrator shell or install via the
Write-Error ("$(Get-Date –f $TIME_STAMP_FORMAT) - $ModuleName module was not found. Please install version $ExpectedVersion of the module.")
throw "$(Get-Date –f $TIME_STAMP_FORMAT) - $ModuleName module was not found. Please install version $ExpectedVersion of the module."
}
else
{
$ExpectedVersionObject = New-Object System.Version($ExpectedVersion)
$ComparisonResult = $ExpectedVersionObject.CompareTo($Module.Version)
if ($ComparisonResult -eq 1)
{
Write-Error ("$(Get-Date –f $TIME_STAMP_FORMAT) - $ModuleName module version $($Module.Version.Major).$($Module.Version.Minor).$($Module.Version.Build) is installed; please update to $($ExpectedVersion) and run again.")
throw "$ModuleName module version $($Module.Version.Major).$($Module.Version.Minor).$($Module.Version.Build) is installed; please update to $($ExpectedVersion) and run again."
}
elseif ($ComparisonResult -eq -1)
{
if ($Module.Version.Major -ne $ExpectedVersion.Major -and $Module.Version.Minor -ne $ExpectedVersion.Minor)
{
Write-Warning "$(Get-Date –f $TIME_STAMP_FORMAT) - This script was tested with $ModuleName module version $($ExpectedVersion)"
Write-Warning "$(Get-Date –f $TIME_STAMP_FORMAT) - Found $ModuleName module version $($Module.Version.Major).$($Module.Version.Minor).$($Module.Version.Build) installed; continuing, but errors might occur"
}
}
}
}
Function GetAuthenticationResult()
{
Param
(
[Parameter(Mandatory=$true, Position=0)] [string] $tenant,
[Parameter(Mandatory=$true, Position=1)] [string] $authUri,
[Parameter(Mandatory=$true, Position=2)] [string] $resourceUri,
[Parameter(Mandatory=$false, Position=3)] [string] $user = $null,
[Parameter(Mandatory=$false)] [string] $prompt = "Auto"
)
$psAadClientId = "1950a258-227b-4e31-a9cf-717495945fc2"
[Uri]$aadRedirectUri = "urn:ietf:wg:oauth:2.0:oob"
$authority = "{0}{1}" -f $authUri, $tenant
write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Authority: '{0}'" -f $authority)
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority,$true
$userId = [Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier]::AnyUser
if (![string]::IsNullOrEmpty($user))
{
$userId = new-object Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier -ArgumentList $user, "OptionalDisplayableId"
}
write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - {0}, {1}, {2}, {3}" -f $resourceUri, $psAadClientId, $aadRedirectUri, $userId.Id)
$authResult = $authContext.AcquireToken($resourceUri, $psAadClientId, $aadRedirectUri, $prompt, $userId)
return $authResult
}
#
# Called if no Azure location is configured for the deployment to let the user chose one location from within the used Azure environment.
# Note: do not use Write-Output since return value is used
#
Function GetAzureLocation()
{
$locations = @();
$index = 1
foreach ($location in $script:AzureLocations)
{
$newLocation = New-Object System.Object
$newLocation | Add-Member -MemberType NoteProperty -Name "Option" -Value $index
$newLocation | Add-Member -MemberType NoteProperty -Name "Location" -Value $location
$locations += $newLocation
$index += 1
}
Write-Host
Write-Host ("Available locations in Azure environment '{0}':" -f $script:AzureEnvironment.Name)
Write-Host
$script:OptionIndex = 1
Write-Host ($locations | Format-Table @{Name='Option';Expression={$script:OptionIndex;$script:OptionIndex+=1};Alignment='right'},@{Name="Location";Expression={$_.Location}} -AutoSize | Out-String).Trim()
Write-Host
$location = ""
while ($location -eq "" -or !(ValidateLocation $location))
{
try
{
[int]$script:OptionIndex = Read-Host 'Select an option from the above location list'
}
catch
{
Write-Host "Must be a number"
continue
}
if ($script:OptionIndex -lt 1 -or $script:OptionIndex -ge $index)
{
continue
}
$location = $script:AzureLocations[$script:OptionIndex - 1]
}
Write-Verbose "$(Get-Date –f $TIME_STAMP_FORMAT) - Azure location '$location' selected."
# Workaround since errors pipe to the output stream
$script:GetOrSetSettingValue = $location
}
Function ValidateLocation()
{
Param (
[Parameter(Mandatory=$true)] [string] $locationToValidate
)
foreach ($location in $script:AzureLocations)
{
if ($location.Replace(' ', '').ToLowerInvariant() -eq $location.Replace(' ', '').ToLowerInvariant())
{
return $true;
}
}
Write-Warning ("$(Get-Date –f $TIME_STAMP_FORMAT) - Location '{0} is not available for this subscription. Please chose a different location." -f $locationToValidate)
Write-Warning "$(Get-Date –f $TIME_STAMP_FORMAT) - Available Locations:"
foreach ($location in $script:AzureLocations)
{
Write-Warning $location
}
return $false
}
Function GetResourceGroup()
{
$resourceGroup = Get-AzureRmResourceGroup -Tag @{"IotSuiteType" = $script:SuiteType} | ?{$_.Name -eq $script:SuiteName}
if ($resourceGroup -eq $null)
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) No resource group found with name '{0}' and type '{1}'" -f $script:SuiteName, $script:SuiteType)
# If the simulation should be updated, it is expected that the resource group exists
if ($script:Command -ne "updatesimulation")
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) GetResourceGroup Location: '{0}, IoTSuiteVersion: '{1}'" -f $script:AzureLocation, $script:IotSuiteVersion)
return New-AzureRmResourceGroup -Name $script:SuiteName -Location $script:AzureLocation -Tag @{"IoTSuiteType" = $script:SuiteType ; "IoTSuiteVersion" = $script:IotSuiteVersion ; "IoTSuiteState" = "Created"}
}
else
{
return $null
}
}
else
{
return Get-AzureRmResourceGroup -Name $script:SuiteName
}
}
Function UpdateResourceGroupState()
{
Param(
[Parameter(Mandatory=$true,Position=1)] [string] $state
)
$resourceGroup = Get-AzureRmResourceGroup -ResourceGroupName $script:ResourceGroupName
if ($resourceGroup -ne $null)
{
$tags = $resourceGroup.Tags
$updated = $false
if ($tags.ContainsKey("IoTSuiteState"))
{
$tags.IoTSuiteState = $state
$updated = $true
}
if ($tags.ContainsKey("IoTSuiteVersion") -and $tags.IoTSuiteVersion -ne $script:IotSuiteVersion)
{
$tags.IoTSuiteVersion = $script:IotSuiteVersion
$updated = $true
}
if (!$updated)
{
$tags += @{"IoTSuiteState" = $state}
}
$resourceGroup = Set-AzureRmResourceGroup -Name $script:ResourceGroupName -Tag $tags
}
}
Function ValidateResourceName()
{
Param(
[Parameter(Mandatory=$true,Position=0)] [string] $resourceBaseName,
[Parameter(Mandatory=$true,Position=1)] [string] $resourceType
)
# Generate a unique name
$resourceUrl = " "
$allowNameReuse = $true
switch ($resourceType.ToLowerInvariant())
{
"microsoft.devices/iothubs"
{
$resourceUrl = $script:IotHubSuffix
}
"microsoft.storage/storageaccounts"
{
$resourceUrl = "blob.{0}" -f $script:AzureEnvironment.StorageEndpointSuffix
$resourceBaseName = $resourceBaseName.Substring(0, [System.Math]::Min(19, $resourceBaseName.Length))
}
"microsoft.web/sites"
{
$resourceUrl = $script:WebsiteSuffix
}
"microsoft.network/publicipaddresses"
{
$resourceBaseName = $resourceBaseName.Substring(0, [System.Math]::Min(40, $resourceBaseName.Length))
}
"microsoft.compute/virtualmachines"
{
return $resourceBaseName.Substring(0, [System.Math]::Min(64, $resourceBaseName.Length))
}
"microsoft.timeseriesinsights/environments"
{
return $resourceBaseName.Substring(0, [System.Math]::Min(64, $resourceBaseName.Length))
}
default {}
}
# Return name for existing resource if exists
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Check if Azure resource: '{0}' (type: '{1}') exists in resource group '{2}'" -f $resourceBaseName, $resourceType, $resourceGroupName)
$resources = Get-AzureRmResource -ResourceGroupName "*$script:ResourceGroupName*" -ResourceType $resourceType -Name "*$resourceBaseName*"
if ($resources -ne $null -and $allowNameReuse)
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Found the resource. Validating exact naming.")
foreach($resource in $resources)
{
if ($resource.ResourceGroupName -eq $script:ResourceGroupName -and $resource.Name.ToLowerInvariant().StartsWith($resourceBaseName.ToLowerInvariant()))
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Resource with matching resource group name and name found.")
return $resource.Name
}
}
}
return GetUniqueResourceName $resourceBaseName $resourceType $resourceUrl
}
Function GetUniqueResourceName()
{
Param(
[Parameter(Mandatory=$true,Position=0)] [string] $resourceBaseName,
[Parameter(Mandatory=$true,Position=1)] [string] $resourceType,
[Parameter(Mandatory=$true,Position=2)] [string] $resourceUrl
)
# retry max 200 times if the random name already exists
$max = 200
$name = $resourceBaseName
while (AzureNameExists $name $resourceType $resourceUrl)
{
$name = "{0}{1:x5}" -f $resourceBaseName, (get-random -max 1048575)
if ($max-- -le 0)
{
Write-Error ("$(Get-Date –f $TIME_STAMP_FORMAT) - Unable to create unique name for resource {0} for url {1}" -f $name, $resourceUrl)
throw ("Unable to create unique name for resource {0} for url {1}" -f $name, $resourceUrl)
}
}
ClearDnsCache
return $name
}
function AzureNameExists () {
Param(
[Parameter(Mandatory=$true,Position=0)] [string] $resourceBaseName,
[Parameter(Mandatory=$true,Position=1)] [string] $resourceType,
[Parameter(Mandatory=$true,Position=2)] [string] $resourceUrl
)
switch ($resourceType.ToLowerInvariant())
{
"microsoft.storage/storageaccounts"
{
return ((Get-AzureRmStorageAccountNameAvailability -Name $resourceBaseName).NameAvailable -eq $false)
}
"microsoft.eventhub/namespaces"
{
return Test-AzureName -ServiceBusNamespace $resourceBaseName
}
"microsoft.web/sites"
{
return Test-AzureName -Website $resourceBaseName
}
"microsoft.devices/iothubs"
{
if($script:CorruptedIotHubDNS)
{
return HostReplyRequest("https://{0}.{1}/devices" -f $resourceBaseName, $resourceUrl)
}
else
{
return HostEntryExists ("{0}.{1}" -f $resourceBaseName, $resourceUrl)
}
}
default
{
return $true
}
}
}
# Detect if DNS server always return fake response which corrupts DNS name availability check.
function DetectIoTHubDNS()
{
$hostName = "nonexistsitesforsure{0:x5}.$script:IotHubSuffix" -f (get-random -max 1048575)
$script:CorruptedIotHubDNS = $false
try
{
if ([Net.Dns]::GetHostEntry($hostName) -ne $null)
{
Write-Output ("IotHub DNS resolution corruption detected for: {0}" -f $hostName)
$script:CorruptedIotHubDNS = $true
}
}
catch
{
Write-Verbose ("IotHub DNS resolution is normal for: {0}" -f $hostName)
}
}
function HostReplyRequest()
{
Param
(
[Parameter(Mandatory=$true,Position=2)] [string] $resourceUrl
)
try
{
Invoke-WebRequest -Uri $resourceUrl
}
catch [System.Net.WebException]
{
if ($_.Exception -ne $null)
{
if ($_.Exception.Status -eq "ConnectFailure")
{
return $false
}
if ($_.Exception.Response.StatusCode -eq "Unauthorized")
{
return $true
}
}
}
return $false
}
Function GetAzureStorageAccount()
{
$storageTempName = $script:SuiteName.ToLowerInvariant().Replace('-','')
$storageAccountName = ValidateResourceName $storageTempName.Substring(0, [System.Math]::Min(19, $storageTempName.Length)) Microsoft.Storage/storageAccounts
$storage = Get-AzureRmStorageAccount -ResourceGroupName $script:ResourceGroupName -Name $storageAccountName -ErrorAction SilentlyContinue
if ($storage -eq $null)
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Creating new storage account: '{0}" -f $storageAccountName)
$storage = New-AzureRmStorageAccount -ResourceGroupName $script:ResourceGroupName -StorageAccountName $storageAccountName -Location $script:AzureLocation -Type $script:StorageSkuName -Kind $script:StorageKind
}
return $storage
}
function GetDnsForPublicIpAddress()
{
return (ValidateResourceName $script:SuiteName.ToLowerInvariant() Microsoft.Network/publicIPAddresses).ToLowerInvariant()
}
function GetAzureIotHubName()
{
return ValidateResourceName $script:SuiteName Microsoft.Devices/iotHubs
}
function GetAzureVmName()
{
return ValidateResourceName $script:SuiteName Microsoft.Compute/VirtualMachines
}
function GetAzureRdxName()
{
return ValidateResourceName $script:SuiteName Microsoft.TimeSeriesInsights/environments
}
Function EnvSettingExists()
{
Param(
[Parameter(Mandatory=$true,Position=0)] $settingName
)
return ($script:DeploymentSettingsXml.Environment.SelectSingleNode("//setting[@name = '$settingName']") -ne $null);
}
Function GetOrSetEnvSetting()
{
Param(
[Parameter(Mandatory=$true,Position=0)] [string] $settingName,
[Parameter(Mandatory=$true,Position=1)] [string] $function
)
$settingValue = GetEnvSetting $settingName $false
if ([string]::IsNullOrEmpty($settingValue))
{
$script:GetOrSetSettingValue = $null
$settingValue = &$function
if ($script:GetOrSetSettingValue -ne $null)
{
$settingValue = $GetOrSetSettingValue
$script:GetOrSetSettingValue = $null
}
PutEnvSetting $settingName $settingValue | Out-Null
}
return $settingValue
}
Function UpdateEnvSetting()
{
Param(
[Parameter(Mandatory=$true,Position=0)] $settingName,
[Parameter(Mandatory=$true,Position=1)] [AllowEmptyString()] $settingValue
)
$currentValue = GetEnvSetting $settingName $false
if ($currentValue -ne $settingValue)
{
PutEnvSetting $settingName $settingValue
}
}
Function GetEnvSetting()
{
Param(
[Parameter(Mandatory=$true,Position=0)] [string] $settingName,
[Parameter(Mandatory=$false,Position=1)] [switch] $errorOnNull = $true
)
$setting = $script:DeploymentSettingsXml.Environment.SelectSingleNode("//setting[@name = '$settingName']")
if ($setting -eq $null)
{
if ($errorOnNull)
{
Write-Error -Category ObjectNotFound -Message ("$(Get-Date –f $TIME_STAMP_FORMAT) - Cannot locate setting '{0}' in deployment settings file {1}." -f $settingName, $script:DeploymentSettingsFile)
throw ("Cannot locate setting '{0}' in deployment settings file {1}." -f $settingName, $script:DeploymentSettingsFile)
}
}
return $setting.value
}
Function PutEnvSetting()
{
Param(
[Parameter(Mandatory=$True,Position=0)] [string] $settingName,
[Parameter(Mandatory=$True,Position=1)] [AllowEmptyString()] [string] $settingValue
)
if (EnvSettingExists $settingName)
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - {0} changed to {1}" -f $settingName, $settingValue)
$script:DeploymentSettingsXml.Environment.SelectSingleNode("//setting[@name = '$settingName']").value = $settingValue
}
else
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Added {0} with value {1}" -f $settingName, $settingValue)
$node = $script:DeploymentSettingsXml.CreateElement("setting")
$node.SetAttribute("name", $settingName) | Out-Null
$node.SetAttribute("value", $settingValue) | Out-Null
$script:DeploymentSettingsXml.Environment.AppendChild($node) | Out-Null
}
$script:DeploymentSettingsXml.Save((Get-Item $script:DeploymentSettingsFile).FullName)
}
#
# Called in case no account is configured to let user chose the account.
# Note: do not use Write-Output since return value is used
#
Function GetAzureAccountInfo()
{
if ($script:PresetAzureAccountName -ne $null -and $script:PresetAzureAccountName -ne "")
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Using preset account name '{0}'" -f $script:PresetAzureAccountName)
$account = Get-AzureAccount $script:PresetAzureAccountName
}
if ($account -eq $null)
{
$accounts = Get-AzureAccount
if ($accounts -eq $null)
{
Write-Verbose "$(Get-Date –f $TIME_STAMP_FORMAT) - Add new Azure account"
$account = Add-AzureAccount -Environment $script:AzureEnvironment.Name
}
else
{
Write-Host "$(Get-Date –f $TIME_STAMP_FORMAT) - Select Azure account to use"
$script:OptionIndex = 1
Write-Host
Write-Host ("Available accounts in Azure environment '{0}':" -f $script:AzureEnvironment.Name)
Write-Host
Write-Host (($accounts | Format-Table @{Name='Option';Expression={$script:OptionIndex;$script:OptionIndex+=1};Alignment='right'}, Id, Subscriptions -AutoSize) | Out-String).Trim()
Write-Host (("{0}" -f $script:OptionIndex).PadLeft(6) + " Use another account")
Write-Host
$account = $null
while ($account -eq $null)
{
try
{
[int]$script:OptionIndex = Read-Host "Select an option from the above account list"
}
catch
{
Write-Host "Must be a number"
continue
}
if ($script:OptionIndex -eq $accounts.length + 1)
{
$account = Add-AzureAccount -Environment $script:AzureEnvironment.Name
break;
}
if ($script:OptionIndex -lt 1 -or $script:OptionIndex -gt $accounts.length)
{
continue
}
$account = $accounts[$script:OptionIndex - 1]
}
}
}
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Account Id to use is '{0}'" -f $account.Id)
if ([string]::IsNullOrEmpty($account.Id))
{
Write-Error -("$(Get-Date –f $TIME_STAMP_FORMAT) - There was no account selected. Please check and try again.")
throw ("There was no account selected. Please check and try again.")
}
# Workaround since errors pipe to the output stream
$script:GetOrSetSettingValue = $account.Id
$script:accountName = $account.Id
}
Function ValidateLoginCredentials()
{
# Validate Azure account
$account = Get-AzureAccount -Name $script:AzureAccountName
if ($account -eq $null)
{
Write-Output ("$(Get-Date –f $TIME_STAMP_FORMAT) - Account '{0}' is unknown in Azure environment '{1}'. Add it." -f $script:AzureAccountName, $script:AzureEnvironment.Name)
$account = Add-AzureAccount -Environment $script:AzureEnvironment.Name
}
if ([string]::IsNullOrEmpty($account.Subscriptions) -or (Get-AzureSubscription -SubscriptionId ($account.Subscriptions -replace '(?:\r\n)',',').split(",")[0]) -eq $null)
{
Write-Output ("$(Get-Date –f $TIME_STAMP_FORMAT) - No subscriptions. Add account")
Add-AzureAccount -Environment $script:AzureEnvironment.Name | Out-Null
}
# Validate Azure RM
$profileFile = ($IotSuiteRootPath + "/$($script:AzureAccountName).user")
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Check for profile file '{0}'" -f $profileFile)
if (Test-Path "$profileFile")
{
Write-Output ("$(Get-Date –f $TIME_STAMP_FORMAT) - Use saved profile from '{0}" -f $profileFile)
$rmProfile = Import-AzureRmContext -Path "$profileFile"
$rmProfileLoaded = ($rmProfile -ne $null) -and ($rmProfile.Context -ne $null) -and ((Get-AzureRmSubscription) -ne $null)
}
if ($rmProfileLoaded -ne $true) {
Write-Output "$(Get-Date –f $TIME_STAMP_FORMAT) - Logging in to your AzureRM account"
try {
Login-AzureRmAccount -EnvironmentName $script:AzureEnvironment.Name -ErrorAction Stop | Out-Null
}
catch
{
Write-Error ("$(Get-Date –f $TIME_STAMP_FORMAT) - The login to the Azure account was not successful. Please run the script again.")
throw ("The login to the Azure account was not successful. Please run the script again.")
}
Save-AzureRmContext -Path "$profileFile"
}
}
Function HostEntryExists()
{
Param(
[Parameter(Mandatory=$true,Position=0)] $hostName
)
try
{
if ([Net.Dns]::GetHostEntry($hostName) -ne $null)
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Found hostname: {0}" -f $hostName)
return $true
}
}
catch {}
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Did not find hostname: {0}" -f $hostName)
return $false
}
Function ClearDnsCache()
{
if ($ClearDns -eq $null)
{
try
{
$ClearDns = CheckCommandAvailability Clear-DnsClientCache
}
catch
{
$ClearDns = $false
}
}
if ($ClearDns)
{
Clear-DnsClientCache
}
}
Function ReplaceFileParameters()
{
Param(
[Parameter(Mandatory=$true,Position=0)] [string] $filePath,
[Parameter(Mandatory=$true,Position=1)] [array] $arguments
)
$fileContent = Get-Content "$filePath" | Out-String
for ($i = 0; $i -lt $arguments.Count; $i++)
{
$fileContent = $fileContent.Replace("{$i}", $arguments[$i])
}
return $fileContent
}
# Generate a random password
# Usage: RandomPassword <length>
# For more information see
# https://blogs.technet.microsoft.com/heyscriptingguy/2013/06/03/generating-a-new-password-with-windows-powershell/
Function RandomPassword ($length = 16)
{
$punc = 46..46
$digits = 48..57
$lcLetters = 65..90
$ucLetters = 97..122
$password = [char](Get-Random -Count 1 -InputObject ($lcLetters)) + [char](Get-Random -Count 1 -InputObject ($ucLetters)) + [char](Get-Random -Count 1 -InputObject ($digits)) + [char](Get-Random -Count 1 -InputObject ($punc))
$password += get-random -Count ($length -4) -InputObject ($punc + $digits + $lcLetters + $ucLetters) | % -begin { $aa = $null } -process {$aa += [char]$_} -end {$aa}
return $password
}
Function CreateAadClientSecret()
{
$newPassword = RandomPassword
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - New Password: {0}" -f $newPassword)
Remove-AzureRmADAppCredential -ApplicationId $script:AadClientId -Force -ErrorAction SilentlyContinue
# create new secret for web app, $secret is converted to PSAD type
# keep $newPassword to be returned as a string
$secret = $newPassword
$startDate = Get-Date
$script:clientSecret = New-AzureRmADAppCredential -ApplicationId $script:AadClientId -StartDate $startDate -EndDate $startDate.AddYears(1) -Password (ConvertTo-SecureString -String $secret -Force –AsPlainText)
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - New Secret Id: {0}" -f $script:clientSecret.KeyId)
return $newPassword
}
#
# Called when no configuration for the AAD tenant to use was found to let the user choose one.
# Note: do not use Write-Output since return value is used
#
Function GetAadTenant()
{
$tenants = Get-AzureRmTenant
if ($tenants.Count -eq 0)
{
Write-Error ("$(Get-Date –f $TIME_STAMP_FORMAT) - No Active Directory domains found for '{0}'" -f $script:AzureAccountName)
throw ("No Active Directory domains found for '{0}'" -f $script:AzureAccountName)
}
if ($tenants.Count -eq 1)
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Only one tenant found, use it. TenantId: '{0}' with IdentifierUri '{1}' exists in Azure environment '{2}'" -f $script:WebAppDisplayName , $script:WebAppIdentifierUri, $script:AzureEnvironment.Name)
$tenantId = $tenants[0].Id
}
else
{
# List Active directories associated with account
$directories = @()
$index = 1
[int]$selectedIndex = -1
foreach ($tenantObj in $tenants)
{
$tenant = $tenantObj.Id
$uri = "{0}{1}/me?api-version=1.6" -f $script:AzureEnvironment.GraphUrl, $tenant
$authResult = GetAuthenticationResult $tenant $script:AzureEnvironment.ActiveDirectoryAuthority $script:AzureEnvironment.GraphUrl $script:AzureAccountName -Prompt "Auto"
$header = $authResult.CreateAuthorizationHeader()
$result = Invoke-RestMethod -Method "GET" -Uri $uri -Headers @{"Authorization"=$header;"Content-Type"="application/json"}
if ($result -ne $null)
{
$directory = New-Object System.Object
$directory | Add-Member -MemberType NoteProperty -Name "Option" -Value $index
$directory | Add-Member -MemberType NoteProperty -Name "Directory Name" -Value ($result.userPrincipalName.Split('@')[1])
$directory | Add-Member -MemberType NoteProperty -Name "Tenant Id" -Value $tenant
$directories += $directory
if ($script:PresetAzureDirectoryName -ne $null -and $script:PresetAzureDirectoryName -eq ($result.userPrincipalName.Split('@')[1]))
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Using preset directory name '{0}'" -f $script:PresetAzureDirectoryName)
$selectedIndex = $index
break
}
$index += 1
}
}
if ($selectedIndex -eq -1)
{
Write-Host "Select an Active Directories to use"
Write-Host
Write-Host "Available Active Directories:"
Write-Host
Write-Host ($directories | Out-String) -NoNewline
while ($selectedIndex -lt 1 -or $selectedIndex -ge $index)
{
try
{
[int]$selectedIndex = Read-Host "Select an option from the above directory list"
}
catch
{
Write-Host "Must be a number"
}
}
}
$tenantId = $tenants[$selectedIndex - 1].Id
}
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - AAD Tenant ID is '{0}'" -f $tenantId)
# Workaround since errors pipe to the output stream
$script:GetOrSetSettingValue = $tenantId -as [string]
}
Function UpdateAadApp($tenantId)
{
# Check for application existence
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Check if application '{0}' with IdentifierUri '{1}' exists in Azure environment '{2}'" -f $script:WebAppDisplayName , $script:WebAppIdentifierUri, $script:AzureEnvironment.Name)
$uri = "{0}{1}/applications?api-version=1.6" -f $script:AzureEnvironment.GraphUrl, $tenantId
$searchUri = "{0}&`$filter=identifierUris/any(uri:uri%20eq%20'{1}')" -f $uri, [System.Web.HttpUtility]::UrlEncode($script:WebAppIdentifierUri)
$authResult = GetAuthenticationResult $tenantId $script:AzureEnvironment.ActiveDirectoryAuthority $script:AzureEnvironment.GraphUrl $script:AzureAccountName
$header = $authResult.CreateAuthorizationHeader()
$result = Invoke-RestMethod -Method "GET" -Uri $searchUri -Headers @{"Authorization"=$header;"Content-Type"="application/json"}
if ($result.value.Count -eq 0)
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Application '{0}' not found, create it with IdentifierUri '{1}'" -f $script:WebAppDisplayName, $script:WebAppIdentifierUri)
$password = RandomPassword
$body = ReplaceFileParameters ("{0}/Application.json" -f $script:DeploymentConfigPath) -arguments @($script:WebAppHomepage, $script:WebAppDisplayName, $script:WebAppIdentifierUri, $password)
$result = Invoke-RestMethod -Method "POST" -Uri $uri -Headers @{"Authorization"=$header;"Content-Type"="application/json"} -Body $body -ErrorAction SilentlyContinue
if ($result -eq $null)
{
Write-Error ("$(Get-Date –f $TIME_STAMP_FORMAT) - Unable to create application '{0}' with IdentifierUri '{1}'" -f $script:WebAppDisplayName, $script:WebAppIdentifierUri)
throw "Unable to create application '$script:WebAppDisplayName'"
}
if ([string]::IsNullOrEmpty($result.appId))
{
Write-Error ("$(Get-Date –f $TIME_STAMP_FORMAT) - Unable to create application '{0}' with IdentifierUri '{1}', returned AppId is null." -f $script:WebAppDisplayName, $script:WebAppIdentifierUri)
throw ("Unable to create application '{0}', returned AppId is null." -f $script:WebAppDisplayName)
}
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Successfully created application '{0}' with Id '{1}' and IdentifierUri '{2}'" -f $result.displayName, $result.appId, $result.identifierUri)
$applicationId = $result.appId
}
else
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Found application '{0}' with Id '{1}' and IdentifierUri '{2}'" -f $result.value[0].displayName, $result.value[0].appId, $result[0].identifierUri)
$applicationId = $result.value[0].appId
}
$script:AadClientId = $applicationId
UpdateEnvSetting "AadClientId" $applicationId
# Check for ServicePrincipal
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Check for service principal in '{0}', tenant '{1}' for application '{2}' with appID '{3}'" -f $script:AzureEnvironment.Name, $tenantId, $script:WebAppDisplayName, $applicationId)
$uri = "{0}{1}/servicePrincipals?api-version=1.6" -f $script:AzureEnvironment.GraphUrl, $tenantId
$searchUri = "{0}&`$filter=appId%20eq%20'{1}'" -f $uri, $applicationId
$result = Invoke-RestMethod -Method "GET" -Uri $searchUri -Headers @{"Authorization"=$header;"Content-Type"="application/json"}
if ($result.value.Count -eq 0)
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - No service principal found. Create one in '{0}', tenant '{1}' for application '{2}' with appID '{3}'" -f $script:AzureEnvironment.Name, $tenantId, $script:WebAppDisplayName, $applicationId)
$body = "{ `"appId`": `"$applicationId`" }"
$result = Invoke-RestMethod -Method "POST" -Uri $uri -Headers @{"Authorization"=$header;"Content-Type"="application/json"} -Body $body -ErrorAction SilentlyContinue
if ($result -eq $null)
{
Write-Error ("$(Get-Date –f $TIME_STAMP_FORMAT) - Unable to create ServicePrincipal for application '{0}' with appID '{1}'" -f $script:WebAppDisplayName, $applicationId)
throw ("Unable to create ServicePrincipal for application '{0}' with appID '{1}'" -f $script:WebAppDisplayName, $applicationId)
}
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Successfully created service principal '{0}' with resource Id '{1}'" -f $result.displayName, $result.objectId)
$resourceId = $result.objectId
$roleId = ($result.appRoles| ?{$_.value -eq "admin"}).Id
}
else
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Found service principal '{0}' with resource Id '{1}'" -f $result.displayName, $result.value[0].objectId)
$resourceId = $result.value[0].objectId
$roleId = ($result.value[0].appRoles| ?{$_.value -eq "admin"}).Id
}
# Check for Assigned User
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Check for app role assigment in '{0}', tenant '{1}' for user with Id '{2}'" -f $script:AzureEnvironment.Name, $tenantId, $authResult.UserInfo.UniqueId)
$uri = "{0}{1}/users/{2}/appRoleAssignments?api-version=1.6" -f $script:AzureEnvironment.GraphUrl, $tenantId, $authResult.UserInfo.UniqueId
$result = Invoke-RestMethod -Method "GET" -Uri $uri -Headers @{"Authorization"=$header;"Content-Type"="application/json"}
if (($result.value | ?{$_.ResourceId -eq $resourceId}) -eq $null)
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Create app role assigment 'principalId' in '{0}', tenant '{1}' for user with Id '{2}'" -f $script:AzureEnvironment.Name, $tenantId, $authResult.UserInfo.UniqueId)
$body = "{ `"id`": `"$roleId`", `"principalId`": `"$($authResult.UserInfo.UniqueId)`", `"resourceId`": `"$resourceId`" }"
$result = Invoke-RestMethod -Method "POST" -Uri $uri -Headers @{"Authorization"=$header;"Content-Type"="application/json"} -Body $body -ErrorAction SilentlyContinue
if ($result -eq $null)
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Unable to create app role assignment for application '{0}' with appID '{1}' for current user - will be Implicit Readonly" -f $script:WebAppDisplayName, $applicationId)
}
else
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Successfully created 'Service Principal' app role assignment for user '{0}' for application '{1}' with appID '{2}''" -f $authResult.UserInfo.UniqueId,$result.resourceDisplayName, $applicationId)
}
}
else
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - User with Id '{0}' has role 'Service Principal' already assigned for the application '{1}' with appID '{2}'" -f $authResult.UserInfo.UniqueId,$result.resourceDisplayName, $applicationId)
}
}
Function InitializeDeploymentSettings()
{
#
# Initialize deployment settings
#
Write-Output ("$(Get-Date –f $TIME_STAMP_FORMAT) - Using deployment settings filename {0}" -f $script:DeploymentSettingsFile)
# read settings into XML variable
if (!(Test-Path "$script:DeploymentSettingsFile"))
{
Copy-Item ("{0}/ConfigurationTemplate.config" -f $script:DeploymentConfigPath) $script:DeploymentSettingsFile | Out-Null
}
$script:DeploymentSettingsXml = [xml](Get-Content "$script:DeploymentSettingsFile")
}
Function InitializeEnvironment()
{
#
# Azure login
#
$script:AzureAccountName = GetOrSetEnvSetting "AzureAccountName" "GetAzureAccountInfo"
Write-Output ("$(Get-Date –f $TIME_STAMP_FORMAT) - Validate Azure account '{0}'" -f $script:AzureAccountName)
ValidateLoginCredentials
if ($script:PresetAzureSubscriptionName -ne $null -and $script:PresetAzuresubscriptionName -ne "")
{
Write-Verbose ("$(Get-Date –f $TIME_STAMP_FORMAT) - Using preset subscription name '{0}'" -f $script:PresetAzureSubscriptionName)
$subscriptionId = Get-AzureRmSubscription -SubscriptionName $script:PresetAzureSubscriptionName
}
#
# Select Azure subscription to use
#
if ([string]::IsNullOrEmpty($subscriptionId))
{
$subscriptionId = GetEnvSetting "SubscriptionId"
if ([string]::IsNullOrEmpty($subscriptionId))
{
Write-Output ("$(Get-Date –f $TIME_STAMP_FORMAT) - Select an Azure subscription to use ")
$subscriptions = Get-AzureRMSubscription
if ($subscriptions.Count -eq 1)
{
$subscriptionId = $subscriptions[0].Id