-
Notifications
You must be signed in to change notification settings - Fork 112
/
Deploy-AzureOptimizationEngine.ps1
1518 lines (1379 loc) · 71 KB
/
Deploy-AzureOptimizationEngine.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
param (
[Parameter(Mandatory = $false)]
[string] $TemplateUri,
[Parameter(Mandatory = $false)]
[string] $AzureEnvironment = "AzureCloud",
[Parameter(Mandatory = $false)]
[switch] $DoPartialUpgrade,
[Parameter(Mandatory = $false)]
[switch] $IgnoreNamingAvailabilityErrors,
[Parameter(Mandatory = $false)]
[string] $SilentDeploymentSettingsPath,
[Parameter(Mandatory = $false)]
[hashtable] $ResourceTags = @{}
)
function ConvertTo-Hashtable {
[CmdletBinding()]
[OutputType('hashtable')]
param (
[Parameter(ValueFromPipeline)]
$InputObject
)
process {
if ($null -eq $InputObject) {
return $null
}
if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [string]) {
$collection = @(
foreach ($object in $InputObject) {
ConvertTo-Hashtable -InputObject $object
}
)
Write-Output -NoEnumerate $collection
} elseif ($InputObject -is [psobject]) {
$hash = @{}
foreach ($property in $InputObject.PSObject.Properties) {
$hash[$property.Name] = ConvertTo-Hashtable -InputObject $property.Value
}
$hash
} else {
$InputObject
}
}
}
function Test-SqlPasswordComplexity {
param (
[string]$Username,
[string]$Password
)
# Check if the username is present in the password
if ($Password -match $Username) {
throw "SQL password cannot contain the SQL username."
return $false
}
# Password must be minimum 8 characters, contains at least one uppercase, lowercase letter, contains at least one digit, contains at least one special character
$regex = '^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,}$'
if ($Password -match $regex) {
Write-Host "SQL password is valid." -ForegroundColor Green
return $true
} else {
throw "Password does not meet the complexity requirements."
return $false
}
}
$ErrorActionPreference = "Stop"
#region Deployment environment settings
$lastDeploymentStatePath = ".\last-deployment-state.json"
$deploymentOptions = @{}
$silentDeploy = $false
# Check if silent deployment settings file exists
if(-not([string]::IsNullOrEmpty($SilentDeploymentSettingsPath)) -and (Test-Path -Path $SilentDeploymentSettingsPath))
{
$silentDeploy = $true
# Get the deployment details from the silent deployment settings file
$silentDepOptions = Get-Content -Path $SilentDeploymentSettingsPath | ConvertFrom-Json
Write-Host "Silent deployment options found." -ForegroundColor Green
$silentDepOptions = ConvertTo-Hashtable -InputObject $silentDepOptions
$silentDepOptions.Keys | ForEach-Object {
$deploymentOptions[$_] = $silentDepOptions[$_]
}
# Validate the silent deployment settings
if (-not($deploymentOptions["SubscriptionId"]))
{
throw "SubscriptionId is required for silent deployment."
}
if (-not($deploymentOptions["NamePrefix"]))
{
throw "NamePrefix is required for silent deployment. Set to 'EmptyNamePrefix' to use own naming convention and specify the needed resource names."
}
if ($deploymentOptions["NamePrefix"].Length -gt 21) {
throw "Name prefix length is larger than the 21 characters limit ($($deploymentOptions["NamePrefix"]))"
}
if ($deploymentOptions["NamePrefix"] -eq "EmptyNamePrefix")
{
if (-not($deploymentOptions["ResourceGroupName"]))
{
throw "ResourceGroupName is required for silent deployment when NamePrefix is set to 'EmptyNamePrefix'."
}
if (-not($deploymentOptions["StorageAccountName"]))
{
throw "StorageAccountName is required for silent deployment when NamePrefix is set to 'EmptyNamePrefix'."
}
if (-not($deploymentOptions["AutomationAccountName"]))
{
throw "AutomationAccountName is required for silent deployment when NamePrefix is set to 'EmptyNamePrefix'."
}
if (-not($deploymentOptions["SqlServerName"]))
{
throw "SqlServerName is required for silent deployment when NamePrefix is set to 'EmptyNamePrefix'."
}
if (-not($deploymentOptions["SqlDatabaseName"]))
{
throw "SqlDatabaseName is required for silent deployment when NamePrefix is set to 'EmptyNamePrefix'."
}
}
if (-not($deploymentOptions["WorkspaceReuse"]) -or ($deploymentOptions["WorkspaceReuse"] -ne "y" -and $deploymentOptions["WorkspaceReuse"] -ne "n"))
{
throw "WorkspaceReuse set to 'y' or 'n' is required for silent deployment."
}
if ($deploymentOptions["WorkspaceReuse"] -eq "y")
{
if (-not($deploymentOptions["WorkspaceName"]))
{
throw "WorkspaceName is required for silent deployment when WorkspaceReuse is set to 'y'."
}
if (-not($deploymentOptions["WorkspaceResourceGroupName"]))
{
throw "WorkspaceResourceGroupName is required for silent deployment when WorkspaceReuse is set to 'y'."
}
}
if (-not($deploymentOptions["DeployWorkbooks"]) -or ($deploymentOptions["DeployWorkbooks"] -ne "y" -and $deploymentOptions["DeployWorkbooks"] -ne "n"))
{
throw "DeployWorkbooks set to 'y' or 'n' is required for silent deployment."
}
if (-not($deploymentOptions["SqlAdmin"]))
{
throw "SqlAdmin is required for silent deployment."
}
if (-not($deploymentOptions["SqlPass"]))
{
throw "SqlPass is required for silent deployment."
}
if (-not($deploymentOptions["TargetLocation"]))
{
throw "TargetLocation is required for silent deployment."
}
if (-not($deploymentOptions["DeployBenefitsUsageDependencies"]))
{
throw "DeployBenefitsUsageDependencies is required for silent deployment."
}
if ($deploymentOptions["DeployBenefitsUsageDependencies"] -eq "y")
{
if (-not($deploymentOptions["CustomerType"]))
{
throw "CustomerType is required for silent deployment when DeployBenefitsUsageDependencies is set to 'y'."
}
if (-not($deploymentOptions["BillingAccountId"]))
{
throw "BillingAccountId is required for silent deployment when DeployBenefitsUsageDependencies is set to 'y'."
}
if (-not($deploymentOptions["CurrencyCode"]))
{
throw "CurrencyCode is required for silent deployment when DeployBenefitsUsageDependencies is set to 'y'."
}
if ($deploymentOptions["CustomerType"] -eq "MCA")
{
if (-not($deploymentOptions["BillingProfileId"]))
{
throw "BillingProfileId is required for silent deployment when CustomerType is set to 'MCA'."
}
}
}
}
if ((Test-Path -Path $lastDeploymentStatePath) -and !$silentDeploy)
{
$depOptions = Get-Content -Path $lastDeploymentStatePath | ConvertFrom-Json
Write-Host $depOptions -ForegroundColor Green
$depOptionsReuse = Read-Host "Found last deployment options above. Do you want to repeat/upgrade last deployment (Y/N)?"
if ("Y", "y" -contains $depOptionsReuse)
{
foreach ($property in $depOptions.PSObject.Properties)
{
$deploymentOptions[$property.Name] = $property.Value
}
}
}
$GitHubOriginalUri = "https://raw.githubusercontent.com/helderpinto/AzureOptimizationEngine/master/azuredeploy.bicep"
if ([string]::IsNullOrEmpty($TemplateUri)) {
$TemplateUri = $GitHubOriginalUri
}
$isTemplateAvailable = $false
try {
Invoke-WebRequest -Uri $TemplateUri | Out-Null
$isTemplateAvailable = $true
}
catch {
Write-Host "The template URL ($TemplateUri) is not available. Please, put it in a publicly accessible HTTPS location." -ForegroundColor Red
}
if (!$isTemplateAvailable) {
throw "Terminating due to template unavailability."
}
if (-not((Test-Path -Path "./azuredeploy.bicep") -and (Test-Path -Path "./azuredeploy-nested.bicep"))) {
throw "Terminating due to template unavailability. Please, change directory to where azuredeploy.bicep and azuredeploy-nested.bicep are located."
}
$cloudDetails = Get-AzEnvironment -Name $AzureEnvironment
$ctx = Get-AzContext
if (-not($ctx)) {
Connect-AzAccount -Environment $AzureEnvironment
$ctx = Get-AzContext
}
else {
if ($ctx.Environment.Name -ne $AzureEnvironment) {
Disconnect-AzAccount -ContextName $ctx.Name
Connect-AzAccount -Environment $AzureEnvironment
$ctx = Get-AzContext
}
}
#endregion
#region Azure subscription choice
Write-Host "Getting Azure subscriptions..." -ForegroundColor Yellow
$subscriptions = Get-AzSubscription | Where-Object { $_.State -eq "Enabled" -and $_.SubscriptionPolicies.QuotaId -notlike "AAD*" }
if ($subscriptions.Count -gt 1) {
$selectedSubscription = -1
for ($i = 0; $i -lt $subscriptions.Count; $i++)
{
if (-not($deploymentOptions["SubscriptionId"]))
{
Write-Output "[$i] $($subscriptions[$i].Name)"
}
else
{
if ($subscriptions[$i].Id -eq $deploymentOptions["SubscriptionId"])
{
$selectedSubscription = $i
break
}
}
}
if (-not($deploymentOptions["SubscriptionId"]))
{
$lastSubscriptionIndex = $subscriptions.Count - 1
while ($selectedSubscription -lt 0 -or $selectedSubscription -gt $lastSubscriptionIndex) {
Write-Output "---"
$selectedSubscription = [int] (Read-Host "Please, select the target subscription for this deployment [0..$lastSubscriptionIndex]")
}
}
if ($selectedSubscription -eq -1)
{
throw "The selected subscription does not exist. Check if you are logged in with the right Microsoft Entra ID user."
}
}
else
{
if ($subscriptions.Count -ne 0)
{
$selectedSubscription = 0
}
else
{
throw "No valid subscriptions found. Only EA, MCA, PAYG or MSDN subscriptions are supported currently."
}
}
if ($subscriptions.Count -eq 0) {
throw "No subscriptions found. Check if you are logged in with the right Microsoft Entra ID account."
}
$subscriptionId = $subscriptions[$selectedSubscription].Id
if (-not($deploymentOptions["SubscriptionId"]))
{
$deploymentOptions["SubscriptionId"] = $subscriptionId
}
if ($ctx.Subscription.Id -ne $subscriptionId) {
$ctx = Select-AzSubscription -SubscriptionId $subscriptionId
}
#endregion
#region Resource naming options
if($silentDeploy)
{
$workspaceReuse = $deploymentOptions["WorkspaceReuse"]
}
else {
$workspaceReuse = $null
}
$deploymentNameTemplate = "{0}" + (Get-Date).ToString("yyMMddHHmmss")
$resourceGroupNameTemplate = "{0}-rg"
$storageAccountNameTemplate = "{0}sa"
$laWorkspaceNameTemplate = "{0}-la"
$automationAccountNameTemplate = "{0}-auto"
$sqlServerNameTemplate = "{0}-sql"
$nameAvailable = $true
if (-not($deploymentOptions["NamePrefix"]))
{
do
{
$namePrefix = Read-Host "Please, enter a unique name prefix for the deployment (max. 21 chars) or existing prefix if updating deployment. If you want instead to individually name all resources, just press ENTER"
if (-not($namePrefix))
{
$namePrefix = "EmptyNamePrefix"
}
}
while ($namePrefix.Length -gt 21)
$deploymentOptions["NamePrefix"] = $namePrefix
}
else {
if ($deploymentOptions["NamePrefix"] -eq "EmptyNamePrefix")
{
$namePrefix = $null
}
else
{
$namePrefix = $deploymentOptions["NamePrefix"]
}
}
if (-not($deploymentOptions["WorkspaceReuse"]))
{
if ($null -eq $workspaceReuse) {
$workspaceReuse = Read-Host "Are you going to reuse an existing Log Analytics workspace (Y/N)?"
}
$deploymentOptions["WorkspaceReuse"] = $workspaceReuse
}
else
{
$workspaceReuse = $deploymentOptions["WorkspaceReuse"]
}
if (-not($deploymentOptions["ResourceGroupName"]))
{
if ([string]::IsNullOrEmpty($namePrefix) -or $namePrefix -eq "EmptyNamePrefix") {
$resourceGroupName = Read-Host "Please, enter the new or existing Resource Group for this deployment"
$deploymentName = $deploymentNameTemplate -f $resourceGroupName
$storageAccountName = Read-Host "Enter the Storage Account name"
$automationAccountName = Read-Host "Automation Account name"
$sqlServerName = Read-Host "Azure SQL Server name"
$sqlDatabaseName = Read-Host "Azure SQL Database name"
if ("N", "n" -contains $workspaceReuse) {
$laWorkspaceName = Read-Host "Log Analytics Workspace"
}
}
else {
$deploymentName = $deploymentNameTemplate -f $namePrefix
$resourceGroupName = $resourceGroupNameTemplate -f $namePrefix
$storageAccountName = $storageAccountNameTemplate -f $namePrefix
$automationAccountName = $automationAccountNameTemplate -f $namePrefix
$sqlServerName = $sqlServerNameTemplate -f $namePrefix
$laWorkspaceName = $laWorkspaceNameTemplate -f $namePrefix
$sqlDatabaseName = "azureoptimization"
}
$deploymentOptions["ResourceGroupName"] = $resourceGroupName
$deploymentOptions["StorageAccountName"] = $storageAccountName
$deploymentOptions["AutomationAccountName"] = $automationAccountName
$deploymentOptions["SqlServerName"] = $sqlServerName
$deploymentOptions["SqlDatabaseName"] = $sqlDatabaseName
$deploymentOptions["WorkspaceName"] = $laWorkspaceName
}
else
{
# With a silent deploy, overrule any custom resource naming if a NamePrefix is provided
if($silentDeploy -and (![string]::IsNullOrEmpty($namePrefix)))
{
$deploymentName = $deploymentNameTemplate -f $namePrefix
$resourceGroupName = $resourceGroupNameTemplate -f $namePrefix
$storageAccountName = $storageAccountNameTemplate -f $namePrefix
$automationAccountName = $automationAccountNameTemplate -f $namePrefix
$sqlServerName = $sqlServerNameTemplate -f $namePrefix
if ("Y", "y" -contains $workspaceReuse) {
$laWorkspaceName = $deploymentOptions["WorkspaceName"]
}
else {
$laWorkspaceName = $laWorkspaceNameTemplate -f $namePrefix
}
$sqlDatabaseName = "azureoptimization"
}
else {
$resourceGroupName = $deploymentOptions["ResourceGroupName"]
$storageAccountName = $deploymentOptions["StorageAccountName"]
$automationAccountName = $deploymentOptions["AutomationAccountName"]
$sqlServerName = $deploymentOptions["SqlServerName"]
$sqlDatabaseName = $deploymentOptions["SqlDatabaseName"]
$laWorkspaceName = $deploymentOptions["WorkspaceName"]
$deploymentName = $deploymentNameTemplate -f $resourceGroupName
}
}
#endregion
#region Resource naming availability checks
Write-Host "Checking name prefix availability..." -ForegroundColor Green
Write-Host "...for the Storage Account..." -ForegroundColor Green
$sa = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName -ErrorAction SilentlyContinue
if ($null -eq $sa) {
$saNameResult = Get-AzStorageAccountNameAvailability -Name $storageAccountName
if (-not($saNameResult.NameAvailable)) {
$nameAvailable = $false
Write-Host "$($saNameResult.Message)" -ForegroundColor Red
}
}
else {
Write-Host "(The Storage Account was already deployed)" -ForegroundColor Green
}
if ("N", "n" -contains $workspaceReuse) {
Write-Host "...for the Log Analytics workspace..." -ForegroundColor Green
$logAnalyticsReuse = $false
$laWorkspaceResourceGroup = $resourceGroupName
$la = Get-AzOperationalInsightsWorkspace -ResourceGroupName $resourceGroupName -Name $laWorkspaceName -ErrorAction SilentlyContinue
if ($null -eq $la) {
$laNameResult = Invoke-WebRequest -Uri "https://portal.loganalytics.io/api/workspaces/IsWorkspaceExists?name=$laWorkspaceName"
if ($laNameResult.Content -eq "true") {
$nameAvailable = $false
Write-Host "The Log Analytics workspace $laWorkspaceName is already taken." -ForegroundColor Red
}
}
else {
Write-Host "(The Log Analytics Workspace was already deployed)" -ForegroundColor Green
}
}
else {
$logAnalyticsReuse = $true
}
Write-Host "...for the Azure SQL Server..." -ForegroundColor Green
$sql = Get-AzSqlServer -ResourceGroupName $resourceGroupName -Name $sqlServerName -ErrorAction SilentlyContinue
if ($null -eq $sql -and -not($sqlServerName -like "*.database.*") -and -not($IgnoreNamingAvailabilityErrors)) {
$SqlServerNameAvailabilityUriPath = "/subscriptions/$subscriptionId/providers/Microsoft.Sql/checkNameAvailability?api-version=2014-04-01"
$body = "{`"name`": `"$sqlServerName`", `"type`": `"Microsoft.Sql/servers`"}"
$sqlNameResult = (Invoke-AzRestMethod -Path $SqlServerNameAvailabilityUriPath -Method POST -Payload $body).Content | ConvertFrom-Json
if (-not($sqlNameResult.available)) {
$nameAvailable = $false
Write-Host "$($sqlNameResult.message) ($sqlServerName)" -ForegroundColor Red
}
}
else {
Write-Host "(The SQL Server was already deployed)" -ForegroundColor Green
}
if (-not($nameAvailable) -and -not($IgnoreNamingAvailabilityErrors))
{
throw "Please, fix naming issues. Terminating execution."
}
Write-Host "Chosen resource names are available for all services" -ForegroundColor Green
#endregion
#region Additional resource options (LA reused, region, SQL user)
if (-not($deploymentOptions["WorkspaceResourceGroupName"]))
{
if ("Y", "y" -contains $workspaceReuse) {
$laWorkspaceName = Read-Host "Please, enter the name of the Log Analytics workspace to be reused"
$laWorkspaceResourceGroup = Read-Host "Please, enter the name of the resource group containing Log Analytics $laWorkspaceName"
$la = Get-AzOperationalInsightsWorkspace -ResourceGroupName $laWorkspaceResourceGroup -Name $laWorkspaceName -ErrorAction SilentlyContinue
if (-not($la)) {
throw "Could not find $laWorkspaceName in resource group $laWorkspaceResourceGroup for the chosen subscription. Aborting."
}
$deploymentOptions["WorkspaceName"] = $laWorkspaceName
$deploymentOptions["WorkspaceResourceGroupName"] = $laWorkspaceResourceGroup
}
}
else
{
$laWorkspaceResourceGroup = $deploymentOptions["WorkspaceResourceGroupName"]
}
$rg = Get-AzResourceGroup -Name $resourceGroupName -ErrorAction SilentlyContinue
if (-not($deploymentOptions["TargetLocation"]))
{
if (-not($rg.Location)) {
Write-Host "Getting Azure locations..." -ForegroundColor Green
$locations = Get-AzLocation | Where-Object { $_.Providers -contains "Microsoft.Automation" -and $_.Providers -contains "Microsoft.Sql" `
-and $_.Providers -contains "Microsoft.OperationalInsights" `
-and $_.Providers -contains "Microsoft.Storage"} | Sort-Object -Property Location
for ($i = 0; $i -lt $locations.Count; $i++) {
Write-Output "[$i] $($locations[$i].location)"
}
$selectedLocation = -1
$lastLocationIndex = $locations.Count - 1
while ($selectedLocation -lt 0 -or $selectedLocation -gt $lastLocationIndex) {
Write-Output "---"
$selectedLocation = [int] (Read-Host "Please, select the target location for this deployment [0..$lastLocationIndex]")
}
$targetLocation = $locations[$selectedLocation].location
}
else {
$targetLocation = $rg.Location
}
$deploymentOptions["TargetLocation"] = $targetLocation
}
else
{
$targetLocation = $deploymentOptions["TargetLocation"]
}
if (-not($deploymentOptions["SqlAdmin"]))
{
$sqlAdmin = Read-Host "Please, input the SQL Admin username"
$deploymentOptions["SqlAdmin"] = $sqlAdmin
}
else
{
$sqlAdmin = $deploymentOptions["SqlAdmin"]
}
if (-not($deploymentOptions["SqlPass"]))
{
$sqlPass = Read-Host "Please, input the SQL Admin ($sqlAdmin) password" -AsSecureString
}
else
{
$sqlPass = $deploymentOptions["SqlPass"]
if(Test-SqlPasswordComplexity -Username $sqlAdmin -Password $sqlPass -ErrorAction SilentlyContinue)
{
Write-Host "Password complexity check passed" -ForegroundColor Green
$sqlPass = ConvertTo-SecureString -AsPlainText $sqlPass -Force
}
else
{
throw "SQL password complexity check failed. Please, fix the password and try again."
}
}
#endregion
#region Partial upgrade dependent resource checks
if (-not($DoPartialUpgrade))
{
$upgrading = $false
}
else
{
$upgrading = $true
if ($null -ne $rg)
{
if ($upgrading -and $null -ne $sa)
{
$containers = Get-AzStorageContainer -Context $sa.Context
}
else
{
$upgrading = $false
Write-Host "Did not find the $storageAccountName Storage Account." -ForegroundColor Yellow
}
if ($upgrading -and $null -ne $sql)
{
$databases = Get-AzSqlDatabase -ServerName $sql.ServerName -ResourceGroupName $resourceGroupName
if (-not($databases | Where-Object { $_.DatabaseName -eq $sqlDatabaseName}))
{
$upgrading = $false
Write-Host "Did not find the $sqlDatabaseName database." -ForegroundColor Yellow
}
}
else
{
if (-not($IgnoreNamingAvailabilityErrors))
{
$upgrading = $false
Write-Host "Did not find the $sqlServerName SQL Server." -ForegroundColor Yellow
}
}
$auto = Get-AzAutomationAccount -ResourceGroupName $resourceGroupName -Name $automationAccountName -ErrorAction SilentlyContinue
if ($null -ne $auto)
{
$runbooks = Get-AzAutomationRunbook -ResourceGroupName $resourceGroupName `
-AutomationAccountName $auto.AutomationAccountName | Where-Object { $_.Name.StartsWith('Export') }
if ($runbooks.Count -lt 3)
{
$upgrading = $false
Write-Host "Did not find existing runbooks in the $automationAccountName Automation Account." -ForegroundColor Yellow
}
}
else
{
$upgrading = $false
Write-Host "Did not find the $automationAccountName Automation Account." -ForegroundColor Yellow
}
}
else
{
$upgrading = $false
}
}
#endregion
$deploymentMessage = "Deploying Azure Optimization Engine to subscription"
if ($upgrading)
{
Write-Host "Looks like this deployment was already done in the past. We will only upgrade runbooks, modules, schedules, variables, storage and the database." -ForegroundColor Yellow
$deploymentMessage = "Upgrading Azure Optimization Engine in subscription"
}
if ($silentDeploy)
{
$continueInput = "Y"
}
else
{
$continueInput = Read-Host "$deploymentMessage $($subscriptions[$selectedSubscription].Name). Continue (Y/N)?"
}
if ("Y", "y" -contains $continueInput) {
# If we deploy silently, be sure to strip the SQL password from the output
if ($silentDeploy)
{
$deploymentOptions.Remove("SqlPass")
}
$deploymentOptions | ConvertTo-Json | Out-File -FilePath $lastDeploymentStatePath -Force
#region Computing schedules base time
$baseTime = (Get-Date).ToUniversalTime().ToString("u")
$upgradingSchedules = $false
$schedules = Get-AzAutomationSchedule -ResourceGroupName $resourceGroupName -AutomationAccountName $automationAccountName -ErrorAction SilentlyContinue
if ($schedules.Count -gt 0) {
$upgradingSchedules = $true
$originalBaseTime = ($schedules | Where-Object { $_.Name.EndsWith("Weekly") } | Sort-Object -Property StartTime | Select-Object -First 1).StartTime.AddHours(-1.25).DateTime
$now = (Get-Date).ToUniversalTime()
$diff = $now.AddHours(-1.25) - $originalBaseTime
$nextWeekDays = [Math]::Ceiling($diff.TotalDays / 7) * 7
$baseTime = $now.AddHours(-1.25).AddDays($nextWeekDays - $diff.TotalDays).ToString("u")
Write-Host "Existing schedules found. Keeping original base time: $baseTime." -ForegroundColor Green
}
else {
Write-Host "Automation schedules base time automatically set to $baseTime." -ForegroundColor Green
}
#endregion
if (-not($upgrading))
{
#region Template-based deployment
$jobSchedules = Get-AzAutomationScheduledRunbook -ResourceGroupName $resourceGroupName -AutomationAccountName $automationAccountName -ErrorAction SilentlyContinue
if ($jobSchedules.Count -gt 0) {
Write-Host "Unregistering previous runbook schedules associations from $automationAccountName..." -ForegroundColor Green
foreach ($jobSchedule in $jobSchedules) {
if ($jobSchedule.ScheduleName.StartsWith("AzureOptimization")) {
Unregister-AzAutomationScheduledRunbook -ResourceGroupName $resourceGroupName -AutomationAccountName $automationAccountName `
-JobScheduleId $jobSchedule.JobScheduleId -Force
}
}
}
Write-Host "Deploying Azure Optimization Engine resources..." -ForegroundColor Green
$deploymentTries = 0
$maxDeploymentTries = 2
$deploymentSucceeded = $false
do {
$deploymentTries++
try {
$deployment = New-AzDeployment -TemplateFile ".\azuredeploy.bicep" -templateLocation $TemplateUri.Replace("azuredeploy.bicep", "") -Location $targetLocation -rgName $resourceGroupName -Name $deploymentName `
-projectLocation $targetlocation -logAnalyticsReuse $logAnalyticsReuse -baseTime $baseTime `
-logAnalyticsWorkspaceName $laWorkspaceName -logAnalyticsWorkspaceRG $laWorkspaceResourceGroup `
-storageAccountName $storageAccountName -automationAccountName $automationAccountName `
-sqlServerName $sqlServerName -sqlDatabaseName $sqlDatabaseName -cloudEnvironment $AzureEnvironment `
-sqlAdminLogin $sqlAdmin -sqlAdminPassword $sqlPass -resourceTags $ResourceTags -WarningAction SilentlyContinue
$deploymentSucceeded = $true
}
catch {
if ($deploymentTries -ge $maxDeploymentTries) {
Write-Host "Failed deployment. Stop trying." -ForegroundColor Yellow
throw $_
}
Write-Host "Failed deployment. Trying once more..." -ForegroundColor Yellow
}
} while (-not($deploymentSucceeded) -and $deploymentTries -lt $maxDeploymentTries)
$spnId = $deployment.Outputs['automationPrincipalId'].Value
#endregion
}
else
{
#region Partial upgrade deployment
$upgradeManifest = Get-Content -Path "./upgrade-manifest.json" | ConvertFrom-Json
Write-Host "Creating missing storage account containers..." -ForegroundColor Green
$upgradeContainers = $upgradeManifest.dataCollection.container
foreach ($container in $upgradeContainers)
{
if (-not($container -in $containers.Name))
{
New-AzStorageContainer -Name $container -Context $sa.Context -Permission Off | Out-Null
Write-Host "$container container created."
}
}
Write-Host "Importing runbooks..." -ForegroundColor Green
$allRunbooks = $upgradeManifest.baseIngest.runbook + $upgradeManifest.dataCollection.runbook + $upgradeManifest.recommendations.runbook + $upgradeManifest.remediations.runbook
$runbookBaseUri = $TemplateUri.Replace("azuredeploy.bicep", "")
$topTemplateJson = "{ `"`$schema`": `"https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#`", " + `
"`"contentVersion`": `"1.0.0.0`", `"resources`": ["
$bottomTemplateJson = "] }"
$runbookDeploymentTemplateJson = $topTemplateJson
for ($i = 0; $i -lt $allRunbooks.Count; $i++)
{
try {
Invoke-WebRequest -Uri ($runbookBaseUri + $allRunbooks[$i].name) | Out-Null
$runbookName = [System.IO.Path]::GetFilenameWithoutExtension($allRunbooks[$i].name)
$runbookJson = "{ `"name`": `"$automationAccountName/$runbookName`", `"type`": `"Microsoft.Automation/automationAccounts/runbooks`", " + `
"`"apiVersion`": `"2018-06-30`", `"location`": `"$targetLocation`", `"tags`": $($ResourceTags | ConvertTo-Json), `"properties`": { " + `
"`"runbookType`": `"PowerShell`", `"logProgress`": false, `"logVerbose`": false, " + `
"`"publishContentLink`": { `"uri`": `"$runbookBaseUri$($allRunbooks[$i].name)`", `"version`": `"$($allRunbooks[$i].version)`" } } }"
$runbookDeploymentTemplateJson += $runbookJson
if ($i -lt $allRunbooks.Count - 1)
{
$runbookDeploymentTemplateJson += ", "
}
Write-Host "$($allRunbooks[$i].name) imported."
}
catch {
Write-Host "$($allRunbooks[$i].name) not imported (not found)." -ForegroundColor Yellow
}
}
$runbookDeploymentTemplateJson += $bottomTemplateJson
$runbooksTemplatePath = "./aoe-runbooks-deployment.json"
$runbookDeploymentTemplateJson | Out-File -FilePath $runbooksTemplatePath -Force
Write-Host "Executing runbooks deployment..." -ForegroundColor Green
New-AzResourceGroupDeployment -TemplateFile $runbooksTemplatePath -ResourceGroupName $resourceGroupName -Name ($deploymentNameTemplate -f "runbooks") | Out-Null
Remove-Item -Path $runbooksTemplatePath -Force
Write-Host "Runbooks update deployed."
Write-Host "Importing modules..." -ForegroundColor Green
$allModules = $upgradeManifest.modules
$modulesDeploymentTemplateJson = $topTemplateJson
for ($i = 0; $i -lt $allModules.Count; $i++)
{
$moduleJson = "{ `"name`": `"$automationAccountName/$($allModules[$i].name)`", `"type`": `"Microsoft.Automation/automationAccounts/modules`", " + `
"`"apiVersion`": `"2018-06-30`", `"location`": `"$targetLocation`", `"tags`": $($ResourceTags | ConvertTo-Json), `"properties`": { " + `
"`"contentLink`": { `"uri`": `"$($allModules[$i].url)`" } } "
if ($allModules[$i].name -ne "Az.Accounts" -and $allModules[$i].name -ne "Microsoft.Graph.Authentication")
{
$moduleJson += ", `"dependsOn`": [ `"Az.Accounts`", `"Microsoft.Graph.Authentication`" ]"
}
$moduleJson += "}"
$modulesDeploymentTemplateJson += $moduleJson
if ($i -lt $allModules.Count - 1)
{
$modulesDeploymentTemplateJson += ", "
}
Write-Host "$($allModules[$i].name) imported."
}
$modulesDeploymentTemplateJson += $bottomTemplateJson
$modulesTemplatePath = "./aoe-modules-deployment.json"
$modulesDeploymentTemplateJson | Out-File -FilePath $modulesTemplatePath -Force
Write-Host "Executing modules deployment..." -ForegroundColor Green
New-AzResourceGroupDeployment -TemplateFile $modulesTemplatePath -ResourceGroupName $resourceGroupName -Name ($deploymentNameTemplate -f "modules") | Out-Null
Remove-Item -Path $modulesTemplatePath -Force
Write-Host "Modules update deployed."
Write-Host "Updating schedules..." -ForegroundColor Green
$allSchedules = $upgradeManifest.schedules
$allScheduledRunbooks = Get-AzAutomationScheduledRunbook -AutomationAccountName $AutomationAccountName -ResourceGroupName $ResourceGroupName
$exportHybridWorkerOption = ($allScheduledRunbooks | Where-Object { $_.RunbookName.StartsWith("Export") })[0].HybridWorker
$ingestHybridWorkerOption = ($allScheduledRunbooks | Where-Object { $_.RunbookName.StartsWith("Ingest") })[0].HybridWorker
$recommendHybridWorkerOption = ($allScheduledRunbooks | Where-Object { $_.RunbookName.StartsWith("Recommend") })[0].HybridWorker
if ($allScheduledRunbooks | Where-Object { $_.RunbookName.StartsWith("Remediate") })
{
$remediateHybridWorkerOption = ($allScheduledRunbooks | Where-Object { $_.RunbookName.StartsWith("Remediate") })[0].HybridWorker
}
$hybridWorkerOption = "None"
if ($exportHybridWorkerOption -or $ingestHybridWorkerOption -or $recommendHybridWorkerOption -or $remediateHybridWorkerOption) {
$hybridWorkerOption = "Export: $exportHybridWorkerOption; Ingest: $ingestHybridWorkerOption; Recommend: $recommendHybridWorkerOption; Remediate: $remediateHybridWorkerOption"
}
Write-Host "Current Hybrid Worker option: $hybridWorkerOption" -ForegroundColor Green
$dataIngestRunbookName = [System.IO.Path]::GetFileNameWithoutExtension(($upgradeManifest.baseIngest | Where-Object { $_.source -eq "dataCollection"}).runbook.name)
$dataExportsToMultiSchedule = $upgradeManifest.dataCollection | Where-Object { $_.exportSchedules.Count -gt 0 }
$recommendationsProcessingRunbooks = $upgradeManifest.baseIngest | Where-Object { $_.source -eq "recommendations" -or $_.source -eq "maintenance"}
foreach ($schedule in $allSchedules)
{
if (-not($schedules | Where-Object { $_.Name -eq $schedule.name }))
{
$scheduleStartTime = (Get-Date $baseTime).Add([System.Xml.XmlConvert]::ToTimeSpan($schedule.offset))
$scheduleNow = (Get-Date).ToUniversalTime()
if ($schedule.frequency -eq "Hour")
{
if ($scheduleNow.AddMinutes(5) -gt $scheduleStartTime)
{
$hoursDiff = ($scheduleNow - $scheduleStartTime).Hours + 1
$scheduleStartTime = $scheduleStartTime.AddHours($hoursDiff)
}
New-AzAutomationSchedule -Name $schedule.name -AutomationAccountName $automationAccountName -ResourceGroupName $resourceGroupName `
-StartTime $scheduleStartTime -HourInterval 1 | Out-Null
}
if ($schedule.frequency -eq "Day")
{
if ($scheduleNow.AddMinutes(5) -gt $scheduleStartTime)
{
$scheduleStartTime = $scheduleStartTime.AddDays(1)
}
New-AzAutomationSchedule -Name $schedule.name -AutomationAccountName $automationAccountName -ResourceGroupName $resourceGroupName `
-StartTime $scheduleStartTime -DayInterval 1 | Out-Null
}
if ($schedule.frequency -eq "Week")
{
if ($scheduleNow.AddMinutes(5) -gt $scheduleStartTime)
{
$scheduleStartTime = $scheduleStartTime.AddDays(7)
}
New-AzAutomationSchedule -Name $schedule.name -AutomationAccountName $automationAccountName -ResourceGroupName $resourceGroupName `
-StartTime $scheduleStartTime -WeekInterval 1 | Out-Null
}
Write-Host "$($schedule.name) schedule created."
}
$scheduledRunbooks = Get-AzAutomationScheduledRunbook -ResourceGroupName $resourceGroupName -AutomationAccountName $automationAccountName `
-ScheduleName $schedule.name
$dataExportsToSchedule = ($upgradeManifest.dataCollection + $upgradeManifest.recommendations) | Where-Object { $_.exportSchedule -eq $schedule.name }
foreach ($dataExport in $dataExportsToSchedule)
{
$runbookName = [System.IO.Path]::GetFileNameWithoutExtension($dataExport.runbook.name)
$runbookType = $runbookName.Split("-")[0]
switch ($runbookType)
{
"Export" {
$hybridWorkerName = $exportHybridWorkerOption
}
"Recommend" {
$hybridWorkerName = $recommendHybridWorkerOption
}
"Ingest" {
$hybridWorkerName = $ingestHybridWorkerOption
}
"Remediate" {
$hybridWorkerName = $remediateHybridWorkerOption
}
Default {
$hybridWorkerName = $null
}
}
if (-not($scheduledRunbooks | Where-Object { $_.RunbookName -eq $runbookName}))
{
if ($hybridWorkerName)
{
Register-AzAutomationScheduledRunbook -ResourceGroupName $resourceGroupName -AutomationAccountName $automationAccountName `
-RunbookName $runbookName -ScheduleName $schedule.name -RunOn $hybridWorkerName | Out-Null
}
else
{
Register-AzAutomationScheduledRunbook -ResourceGroupName $resourceGroupName -AutomationAccountName $automationAccountName `
-RunbookName $runbookName -ScheduleName $schedule.name | Out-Null
}
Write-Host "Added $($schedule.name) schedule to $hybridWorkerName $runbookName runbook"
}
}
foreach ($dataExport in $dataExportsToMultiSchedule)
{
$exportSchedule = $dataExport.exportSchedules | Where-Object { $_.schedule -eq $schedule.name }
if ($exportSchedule)
{
$runbookName = [System.IO.Path]::GetFileNameWithoutExtension($dataExport.runbook.name)
$runbookType = $runbookName.Split("-")[0]
switch ($runbookType)
{
"Export" {
$hybridWorkerName = $exportHybridWorkerOption
}
"Recommend" {
$hybridWorkerName = $recommendHybridWorkerOption
}
"Ingest" {
$hybridWorkerName = $ingestHybridWorkerOption
}
"Remediate" {
$hybridWorkerName = $remediateHybridWorkerOption
}
Default {
$hybridWorkerName = $null
}
}
if (-not($scheduledRunbooks | Where-Object { $_.RunbookName -eq $runbookName -and $_.ScheduleName -eq $schedule.name}))
{
$params = @{}
$exportSchedule.parameters.PSObject.Properties | ForEach-Object {
$params[$_.Name] = $_.Value
}
if ($hybridWorkerName)
{
Register-AzAutomationScheduledRunbook -ResourceGroupName $resourceGroupName -AutomationAccountName $automationAccountName `
-RunbookName $runbookName -ScheduleName $schedule.name -RunOn $hybridWorkerName -Parameters $params | Out-Null
}
else
{
Register-AzAutomationScheduledRunbook -ResourceGroupName $resourceGroupName -AutomationAccountName $automationAccountName `
-RunbookName $runbookName -ScheduleName $schedule.name -Parameters $params | Out-Null
}
Write-Host "Added $($schedule.name) schedule to $hybridWorkerName $runbookName runbook."
}
}
}
$dataIngestToSchedule = $upgradeManifest.dataCollection | Where-Object { $_.ingestSchedule -eq $schedule.name }
foreach ($dataIngest in $dataIngestToSchedule)
{
$hybridWorkerName = $ingestHybridWorkerOption
if (-not($scheduledRunbooks | Where-Object { $_.RunbookName -eq $dataIngestRunbookName}))
{
$params = @{"StorageSinkContainer"=$dataIngest.container}
if ($hybridWorkerName)
{
Register-AzAutomationScheduledRunbook -ResourceGroupName $resourceGroupName -AutomationAccountName $automationAccountName `
-RunbookName $dataIngestRunbookName -ScheduleName $schedule.name -RunOn $hybridWorkerName -Parameters $params | Out-Null
}
else
{
Register-AzAutomationScheduledRunbook -ResourceGroupName $resourceGroupName -AutomationAccountName $automationAccountName `
-RunbookName $dataIngestRunbookName -ScheduleName $schedule.name -Parameters $params | Out-Null
}
Write-Host "Added $($schedule.name) schedule to $hybridWorkerName $dataIngestRunbookName runbook."
}
}
foreach ($recommendationsProcessingRunbook in $recommendationsProcessingRunbooks)
{
$runbookName = [System.IO.Path]::GetFileNameWithoutExtension($recommendationsProcessingRunbook.runbook.name)
$hybridWorkerName = $ingestHybridWorkerOption
if ($recommendationsProcessingRunbook.schedule -eq $schedule.name -and -not($scheduledRunbooks | Where-Object { $_.RunbookName -eq $runbookName}))
{
if ($hybridWorkerName)
{
Register-AzAutomationScheduledRunbook -ResourceGroupName $resourceGroupName -AutomationAccountName $automationAccountName `
-RunbookName $runbookName -ScheduleName $schedule.name -RunOn $hybridWorkerName | Out-Null
}
else
{
Register-AzAutomationScheduledRunbook -ResourceGroupName $resourceGroupName -AutomationAccountName $automationAccountName `
-RunbookName $runbookName -ScheduleName $schedule.name | Out-Null
}
Write-Host "Added $($schedule.name) schedule to $hybridWorkerName $runbookName runbook."
}
}
}
Write-Host "Updating variables..." -ForegroundColor Green
$allVariables = $upgradeManifest.dataCollection.requiredVariables + $upgradeManifest.recommendations.requiredVariables + $upgradeManifest.remediations.requiredVariables
foreach ($variable in $allVariables)
{
$existingVariables = Get-AzAutomationVariable -ResourceGroupName $resourceGroupName -AutomationAccountName $automationAccountName
if (-not($existingVariables | Where-Object { $_.Name -eq $variable.name }))
{
New-AzAutomationVariable -Name $variable.name -AutomationAccountName $automationAccountName -ResourceGroupName $resourceGroupName `
-Value $variable.defaultValue -Encrypted $false | Out-Null
Write-Host "$($variable.name) variable created."
}
}