Repository navigation
Expand file tree
/
Copy pathCreate-AutomationAccount.ps1
More file actions
executable file
·1713 lines (1624 loc) · 100 KB
/
Copy pathCreate-AutomationAccount.ps1
File metadata and controls
executable file
·1713 lines (1624 loc) · 100 KB
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
#Requires -Version 2.0
<#
Copyright (c) Alya Consulting, 2019-2026
This file is part of the Alya Base Configuration.
https://alyaconsulting.ch/Solutions/AlyaBasisKonfiguration
The Alya Base Configuration is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Alya Base Configuration is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details: https://www.gnu.org/licenses/gpl-3.0.txt
Diese Datei ist Teil der Alya Basis Konfiguration.
https://alyaconsulting.ch/Solutions/AlyaBasisKonfiguration
Die Alya Basis Konfiguration ist eine Freie Software: Sie können sie unter den
Bedingungen der GNU General Public License, wie von der Free Software
Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder neueren
veröffentlichten Version, weiter verteilen und/oder modifizieren.
Die Alya Basis Konfiguration wird in der Hoffnung, dass sie nützlich sein wird,
aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FUER EINEN BESTIMMTEN ZWECK.
Siehe die GNU General Public License fuer weitere Details:
https://www.gnu.org/licenses/gpl-3.0.txt
History:
Date Author Description
---------- -------------------- ----------------------------
14.11.2019 Konrad Brunner Initial Version
31.05.2023 Konrad Brunner Fixes and enhancements
06.02.2026 Konrad Brunner Added powershell documentation
16.09.2026 Konrad Brunner Use Get-CurrentAzAdPrincipal to support service principal logins
#>
<#
.SYNOPSIS
Creates and configures an Azure Automation Account with necessary identities, permissions, key vault access, and runbooks.
.DESCRIPTION
The Create-AutomationAccount.ps1 script automates the creation and configuration of an Azure Automation Account within a defined resource group. It ensures required Azure modules are installed, resource providers are registered, and necessary infrastructure such as Key Vaults, resource groups, and log analytics workspaces are available. The script sets RBAC permissions for users, managed identities, and automation service principals. It creates and assigns certificates, RunAs accounts, and associated Azure AD applications. The script optionally deploys additional runbooks for group updating, VM start/stop automation, and PowerShell 7 runtime environment preparation. It also manages diagnostic settings and module update automation.
.PARAMETER UpdateRunbooks
Indicates whether existing runbooks should be updated or recreated. Default is $true.
.PARAMETER DeployGroupUpdater
Specifies whether to deploy the runbook responsible for updating Azure AD groups such as AllInternals and AllExternals. Default is $false.
.PARAMETER DeployStartStopVm
Indicates whether to deploy and schedule the runbook responsible for starting and stopping virtual machines based on defined tag times. Default is $true.
.PARAMETER PreparePs7RuntimeEnv
Specifies whether to set up and configure PowerShell 7 runtime environments within the automation account. Default is $true.
.INPUTS
None. The script uses environmental variables defined in the loaded configuration script.
.OUTPUTS
Log file written to the automation logs directory summarizing execution steps and results.
.EXAMPLE
PS> .\Create-AutomationAccount.ps1 -UpdateRunbooks $true -DeployGroupUpdater $true -DeployStartStopVm $true -PreparePs7RuntimeEnv $true
.NOTES
Copyright : (c) Alya Consulting, 2019-2026
Author : Konrad Brunner
License : GNU General Public License v3.0 or later (https://www.gnu.org/licenses/gpl-3.0.txt)
Base Configuration : https://alyaconsulting.ch/Solutions/AlyaBasisKonfiguration.
#>
[CmdletBinding()]
Param(
[bool]$UpdateRunbooks = $true,
[bool]$DeployGroupUpdater = $false,
[bool]$DeployStartStopVm = $false,
[bool]$DeploySharePointRunAsApp = $true,
[bool]$PreparePs5Runbooks = $false,
[bool]$PreparePs7RuntimeEnv = $true
)
# Loading configuration
. $PSScriptRoot\..\..\01_ConfigureEnv.ps1
# Starting Transcript
Start-Transcript -Path "$($AlyaLogs)\scripts\automation\Create-AutomationAccount-$($AlyaTimeString).log" -IncludeInvocationHeader -Force | Out-Null
# Constants
$ResourceGroupName = "$($AlyaNamingPrefix)resg$($AlyaResIdAutomation)"
$AutomationAccountName = "$($AlyaNamingPrefix)aacc$($AlyaResIdAutomationAccount)"
$KeyVaultName = "$($AlyaNamingPrefix)keyv$($AlyaResIdMainKeyVault)"
$KeyVaultResourceGroupName = "$($AlyaNamingPrefix)resg$($AlyaResIdMainInfra)"
$SubscriptionNames = @($AlyaSubscriptionName)
$SolutionScriptsRoot = "$($AlyaScripts)\automation"
$SolutionDataRoot = "$($AlyaData)\automation"
if ($true -eq $AlyaResEnableInsightsAndAlerts)
{
$AnalyticsResourceGroupName = "$($AlyaNamingPrefix)resg$($AlyaResIdAuditing)"
$AnalyticsStorageAccountName = "$($AlyaNamingPrefix)strg$($AlyaResIdAuditStorage)"
$AnalyticsWrkspcName = "$($AlyaNamingPrefix)loga$($AlyaResIdLogAnalytics)"
}
if (-Not (Test-Path $SolutionDataRoot))
{
$null = New-Item -Path $SolutionDataRoot -ItemType Directory -Force
}
if ($AlyaSubscriptionNameTest -and $AlyaSubscriptionNameTest -ne $AlyaSubscriptionName)
{
$SubscriptionNames += $AlyaSubscriptionNameTest
}
# Checking modules
Write-Host "Checking modules" -ForegroundColor $CommandInfo
Install-ModuleIfNotInstalled "Az.Accounts"
Install-ModuleIfNotInstalled "Az.Resources"
Install-ModuleIfNotInstalled "Az.KeyVault"
Install-ModuleIfNotInstalled "Az.Automation"
if ($true -eq $AlyaResEnableInsightsAndAlerts)
{
Install-ModuleIfNotInstalled "Az.OperationalInsights"
Install-ModuleIfNotInstalled "Az.Monitor"
}
Install-ModuleIfNotInstalled "Microsoft.Graph.Authentication"
Install-ModuleIfNotInstalled "Microsoft.Graph.Beta.Identity.SignIns"
Install-ModuleIfNotInstalled "Microsoft.Graph.Beta.Applications"
# Logins
LoginTo-Az -SubscriptionName $AlyaSubscriptionName
LoginTo-MgGraph -Scopes @("Directory.Read.All","AppRoleAssignment.ReadWrite.All","Application.ReadWrite.All")
# =============================================================
# Azure stuff
# =============================================================
Write-Host "`n`n=====================================================" -ForegroundColor $CommandInfo
Write-Host "Automation | Create-AutomationAccount | AZURE" -ForegroundColor $CommandInfo
Write-Host "=====================================================`n" -ForegroundColor $CommandInfo
# Getting context
$Context = Get-AzContext
if (-Not $Context)
{
Write-Error "Can't get Az context! Not logged in?" -ErrorAction Continue
Exit 1
}
# Setting variable
$AlyaSubscriptionIds = ""
foreach ($AlyaSubscriptionName in ($AlyaAllSubscriptions | Select-Object -Unique))
{
$sub = Get-AzSubscription -SubscriptionName $AlyaSubscriptionName
if (-Not $AlyaSubscriptionIds.Contains($sub.Id))
{
if (-Not [string]::IsNullOrEmpty($AlyaSubscriptionIds))
{
$AlyaSubscriptionIds += ","
}
$AlyaSubscriptionIds += $sub.Id
}
}
# Checking resource provider registration
Write-Host "Checking resource provider registration Microsoft.KeyVault" -ForegroundColor $CommandInfo
$resProv = Get-AzResourceProvider -ProviderNamespace "Microsoft.KeyVault" -Location $AlyaLocation
if (-Not $resProv -or $resProv.Count -eq 0 -or $resProv[0].RegistrationState -ne "Registered")
{
Write-Warning "Resource provider Microsoft.KeyVault not registered. Registering now resource provider Microsoft.KeyVault"
Register-AzResourceProvider -ProviderNamespace "Microsoft.KeyVault" | Out-Null
do
{
Start-Sleep -Seconds 5
$resProv = Get-AzResourceProvider -ProviderNamespace "Microsoft.KeyVault" -Location $AlyaLocation
} while ($resProv[0].RegistrationState -ne "Registered")
}
# Checking resource provider registration
Write-Host "Checking resource provider registration Microsoft.Automation" -ForegroundColor $CommandInfo
$resProv = Get-AzResourceProvider -ProviderNamespace "Microsoft.Automation" -Location $AlyaLocation
if (-Not $resProv -or $resProv.Count -eq 0 -or $resProv[0].RegistrationState -ne "Registered")
{
Write-Warning "Resource provider Microsoft.Automation not registered. Registering now resource provider Microsoft.Automation"
Register-AzResourceProvider -ProviderNamespace "Microsoft.Automation" | Out-Null
do
{
Start-Sleep -Seconds 5
$resProv = Get-AzResourceProvider -ProviderNamespace "Microsoft.Automation" -Location $AlyaLocation
} while ($resProv[0].RegistrationState -ne "Registered")
}
if ($true -eq $AlyaResEnableInsightsAndAlerts)
{
# Checking resource provider registration
Write-Host "Checking resource provider registration Microsoft.Insights" -ForegroundColor $CommandInfo
$resProv = Get-AzResourceProvider -ProviderNamespace "Microsoft.Insights" -Location $AlyaLocation
if (-Not $resProv -or $resProv.Count -eq 0 -or $resProv[0].RegistrationState -ne "Registered")
{
Write-Warning "Resource provider Microsoft.Insights not registered. Registering now resource provider Microsoft.Insights"
Register-AzResourceProvider -ProviderNamespace "Microsoft.Insights" | Out-Null
do
{
Start-Sleep -Seconds 5
$resProv = Get-AzResourceProvider -ProviderNamespace "Microsoft.Insights" -Location $AlyaLocation
} while ($resProv[0].RegistrationState -ne "Registered")
}
}
# Checking subscriptions
Write-Host "Checking subscriptions" -ForegroundColor $CommandInfo
$Subscriptions = ""
foreach ($SubscriptionName in $SubscriptionNames)
{
$Subs = Get-AzSubscription -SubscriptionName $SubscriptionName -WarningAction SilentlyContinue
$Subscriptions += $Subs.SubscriptionId + ","
}
$Subscriptions = $Subscriptions.TrimEnd(",")
# Checking ressource group
Write-Host "Checking ressource group for automation account" -ForegroundColor $CommandInfo
$ResGrp = Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue
if (-Not $ResGrp)
{
Write-Warning "Ressource Group not found. Creating the Ressource Group $ResourceGroupName"
$ResGrp = New-AzResourceGroup -Name $ResourceGroupName -Location $AlyaLocation -Tag @{displayName="Automation";ownerEmail=$Context.Account.Id}
}
else
{
Write-Host "Updating"
$null = Set-AzResourceGroup -Name $ResourceGroupName -Tag @{displayName="Automation";ownerEmail=$Context.Account.Id}
}
# Checking KeyVault ressource group
Write-Host "Checking KeyVault ressource group for keyvault" -ForegroundColor $CommandInfo
$ResGrpKeyVault = Get-AzResourceGroup -Name $KeyVaultResourceGroupName -ErrorAction SilentlyContinue
if (-Not $ResGrpKeyVault)
{
throw "KeyVault Ressource Group not found. Please create the Ressource Group $KeyVaultResourceGroupName"
}
# Checking key vault
Write-Host "Checking key vault" -ForegroundColor $CommandInfo
$KeyVault = Get-AzKeyVault -ResourceGroupName $KeyVaultResourceGroupName -VaultName $KeyVaultName -ErrorAction SilentlyContinue
if (-Not $KeyVault)
{
throw "Key Vault not found. Please create the Key Vault $KeyVaultName"
}
# Setting own key vault access
Write-Host "Setting own key vault access" -ForegroundColor $CommandInfo
$user = Get-CurrentAzAdPrincipal
if ($KeyVault.EnableRbacAuthorization)
{
$RoleAssignment = Get-AzRoleAssignment -RoleDefinitionName "Key Vault Administrator" -ObjectId $user.Id -Scope $KeyVault.ResourceId -ErrorAction SilentlyContinue | Where-Object { $_.Scope -eq $KeyVault.ResourceId }
$Retries = 0;
While ($null -eq $RoleAssignment -and $Retries -le 6)
{
$RoleAssignment = New-AzRoleAssignment -RoleDefinitionName "Key Vault Administrator" -ObjectId $user.Id -Scope $KeyVault.ResourceId -ErrorAction SilentlyContinue
Start-Sleep -s 10
$RoleAssignment = Get-AzRoleAssignment -RoleDefinitionName "Key Vault Administrator" -ObjectId $user.Id -Scope $KeyVault.ResourceId -ErrorAction SilentlyContinue | Where-Object { $_.Scope -eq $KeyVault.ResourceId }
$Retries++;
}
if ($Retries -gt 6)
{
throw "Was not able to set role assigment 'Key Vault Administrator' for user $($user.Id) on scope $($KeyVault.ResourceId)"
}
}
else
{
Set-AzKeyVaultAccessPolicy -VaultName $KeyVault.VaultName -ObjectId $user.Id -PermissionsToCertificates "All" -PermissionsToSecrets "All" -PermissionsToKeys "All" -PermissionsToStorage "All" -ErrorAction Continue
}
# Checking azure key vault certificate
Write-Host "Checking azure key vault certificate" -ForegroundColor $CommandInfo
$AzureCertifcateAssetName = "AzureRunAsCertificate"
$AzureCertificateName = $AutomationAccountName + $AzureCertifcateAssetName
$AzureKeyVaultCertificate = Get-AzKeyVaultCertificate -VaultName $KeyVaultName -Name $AzureCertificateName -ErrorAction SilentlyContinue
if ($AzureKeyVaultCertificate)
{
if ($AzureKeyVaultCertificate.Expires -lt (Get-Date).AddMonths(3))
{
Write-Host " Certificate in key vault needs update"
$AzureKeyVaultCertificate = $null
}
}
if (-Not $AzureKeyVaultCertificate)
{
Write-Warning "Key Vault certificate not found or needs update. Creating the certificate $AzureCertificateName"
$SelfSignedCertNoOfMonthsUntilExpired = 120
$SelfSignedCertPlainPassword = "-"+[Guid]::NewGuid().ToString()+"]"
$PfxCertPathForRunAsAccount = Join-Path $env:TEMP ($AzureCertificateName + ".pfx")
$CerPassword = ConvertTo-SecureString $SelfSignedCertPlainPassword -AsPlainText -Force
Clear-Variable -Name "SelfSignedCertPlainPassword" -Force -ErrorAction SilentlyContinue
$Cert = New-SelfSignedCertificate -Subject "CN=$AzureCertificateName" -CertStoreLocation Cert:\CurrentUser\My `
-KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" `
-NotBefore (Get-Date).AddDays(-1) -NotAfter (Get-Date).AddMonths($SelfSignedCertNoOfMonthsUntilExpired) -HashAlgorithm SHA256
Export-PfxCertificate -Cert ("Cert:\CurrentUser\My\" + $Cert.Thumbprint) -FilePath $PfxCertPathForRunAsAccount -Password $CerPassword -Force | Write-Verbose
$AzureKeyVaultCertificate = Import-AzKeyVaultCertificate -VaultName $KeyVaultName -Name $AzureCertificateName -FilePath $PfxCertPathForRunAsAccount -Password $CerPassword
$AzureKeyVaultCertificate = Get-AzKeyVaultCertificate -VaultName $KeyVaultName -Name $AzureCertificateName
Remove-Item -Path $PfxCertPathForRunAsAccount -Force -ErrorAction SilentlyContinue | Out-Null
}
try
{
#Exporting certificate
Write-Host "Exporting certificate" -ForegroundColor $CommandInfo
$PfxCertPathForRunAsAccount = Join-Path $env:TEMP ($AzureCertificateName + ".pfx")
$PfxCertPlainPasswordForRunAsAccount = "Alya-" + [Guid]::NewGuid().ToString().Substring(0, 8) + "-Consulting"
#Getting the certificate
$CertificateRetrieved = Get-AzKeyVaultSecret -VaultName $KeyVaultName -Name $AzureCertificateName
$CertificateBytes = [System.Convert]::FromBase64String(($CertificateRetrieved.SecretValue | Foreach-Object { [System.Net.NetworkCredential]::new("", $_).Password }))
$CertCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$CertCollection.Import($CertificateBytes, $null, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
#Export the .pfx file
$ProtectedCertificateBytes = $CertCollection.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $PfxCertPlainPasswordForRunAsAccount)
[System.IO.File]::WriteAllBytes($PfxCertPathForRunAsAccount, $ProtectedCertificateBytes)
#Read the .pfx file
$PfxCert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @($PfxCertPathForRunAsAccount, $PfxCertPlainPasswordForRunAsAccount)
$CerKeyValue = [System.Convert]::ToBase64String($PfxCert.GetRawCertData())
$CerThumbprint = [System.Convert]::ToBase64String($PfxCert.GetCertHash())
$CerThumbprintString = $PfxCert.Thumbprint
$CerStartDate = $PfxCert.NotBefore
$CerEndDate = $PfxCert.NotAfter
# Checking automation account
Write-Host "Checking automation account" -ForegroundColor $CommandInfo
$AutomationAccount = Get-AzAutomationAccount -ResourceGroupName $ResourceGroupName -Name $AutomationAccountName -ErrorAction SilentlyContinue
if (-Not $AutomationAccount)
{
Write-Warning "Automation Account not found. Creating the Automation Account $AutomationAccountName"
$AutomationAccount = New-AzAutomationAccount -ResourceGroupName $ResourceGroupName -Name $AutomationAccountName -Location $AlyaLocation
}
if ($true -eq $AlyaResEnableInsightsAndAlerts)
{
# Checking ressource group
Write-Host "Checking analytics ressource group" -ForegroundColor $CommandInfo
$ResGrpParent = Get-AzResourceGroup -Name $AnalyticsResourceGroupName -ErrorAction SilentlyContinue
if (-Not $ResGrpParent)
{
throw "Does not exist. Please create it first with the script \scripts\azure\Create-AzureLogAnalyticsWorkspace.ps1."
}
# Checking storage account
Write-Host "Checking analytics storage account" -ForegroundColor $CommandInfo
$StrgAccountParent = Get-AzStorageAccount -ResourceGroupName $AnalyticsResourceGroupName -Name $AnalyticsStorageAccountName -ErrorAction SilentlyContinue
if (-Not $StrgAccountParent)
{
throw "Does not exist. Please create it first with the script \scripts\azure\Create-AzureLogAnalyticsWorkspace.ps1."
}
# Checking log analytics workspace
Write-Host "Checking log analytics workspace $AnalyticsWrkspcName" -ForegroundColor $CommandInfo
$LogAnaWrkspcParent = Get-AzOperationalInsightsWorkspace -ResourceGroupName $AnalyticsResourceGroupName -Name $AnalyticsWrkspcName -ErrorAction SilentlyContinue
if (-Not $LogAnaWrkspcParent)
{
throw "Does not exist. Please create it first with the script \scripts\azure\Create-AzureLogAnalyticsWorkspace.ps1."
}
# Setting diagnostic setting automation account
$AutomationAccount = Get-AzAutomationAccount -ResourceGroupName $ResourceGroupName -Name $AutomationAccountName -ErrorAction SilentlyContinue
$AutomationAccountId = "/subscriptions/$($AutomationAccount.SubscriptionId)/resourceGroups/$($AutomationAccount.ResourceGroupName)/providers/Microsoft.Automation/automationAccounts/$AutomationAccountName"
$DiagnosticRuleName = "$AutomationAccountName-diag"
Write-Host "Setting diagnostic setting $DiagnosticRuleName" -ForegroundColor $CommandInfo
$catListLog = @(); $catListMetric = @()
Get-AzDiagnosticSettingCategory -ResourceId $AutomationAccountId | ForEach-Object {
if ($_.CategoryType -eq "Logs")
{
$catListLog += (New-AzDiagnosticSettingLogSettingsObject -Category $_.Name -Enabled $true)
}
else
{
$catListMetric += (New-AzDiagnosticSettingMetricSettingsObject -Category $_.Name -Enabled $true)
}
}
$null = New-AzDiagnosticSetting -Name $DiagnosticRuleName -ResourceId $AutomationAccountId -Log $catListLog -Metric $catListMetric -WorkspaceId $LogAnaWrkspcParent.ResourceId -StorageAccountId $StrgAccountParent.Id
}
# Checking automation account identity
Write-Host "Checking automation account identity" -ForegroundColor $CommandInfo
if (-Not $AutomationAccount.Identity)
{
Set-AzAutomationAccount -ResourceGroupName $ResourceGroupName -Name $AutomationAccountName -AssignSystemIdentity
$AutomationAccount = Get-AzAutomationAccount -ResourceGroupName $ResourceGroupName -Name $AutomationAccountName -ErrorAction SilentlyContinue
while (-Not $AutomationAccount.Identity.PrincipalId)
{
$AutomationAccount = Get-AzAutomationAccount -ResourceGroupName $ResourceGroupName -Name $AutomationAccountName -ErrorAction SilentlyContinue
Write-Host "Waiting for Automation Account Identity"
if (-Not $AutomationAccount.Identity.PrincipalId) { Start-Sleep -Seconds 5 }
}
}
# Setting automation account identity key vault access
Write-Host "Setting automation account identity key vault access" -ForegroundColor $CommandInfo
$retries = 10
while ($true)
{
try {
if ($KeyVault.EnableRbacAuthorization)
{
$RoleAssignment = Get-AzRoleAssignment -RoleDefinitionName "Key Vault Administrator" -ObjectId $AutomationAccount.Identity.PrincipalId -Scope $KeyVault.ResourceId -ErrorAction Continue | Where-Object { $_.Scope -eq $KeyVault.ResourceId }
$Retries = 0;
While ($null -eq $RoleAssignment -and $Retries -le 6)
{
$RoleAssignment = New-AzRoleAssignment -RoleDefinitionName "Key Vault Administrator" -ObjectId $AutomationAccount.Identity.PrincipalId -Scope $KeyVault.ResourceId -ErrorAction Continue
Start-Sleep -s 10
$RoleAssignment = Get-AzRoleAssignment -RoleDefinitionName "Key Vault Administrator" -ObjectId $AutomationAccount.Identity.PrincipalId -Scope $KeyVault.ResourceId -ErrorAction Continue | Where-Object { $_.Scope -eq $KeyVault.ResourceId }
$Retries++;
}
if ($Retries -gt 6)
{
throw "Was not able to set role assigment 'Key Vault Administrator' for app $($AutomationAccount.Identity.PrincipalId) on scope $($KeyVault.ResourceId)"
}
}
else
{
Set-AzKeyVaultAccessPolicy -VaultName $KeyVaultName -ObjectId $AutomationAccount.Identity.PrincipalId -PermissionsToCertificates "All" -PermissionsToSecrets "All" -ErrorAction Stop
}
break
}
catch {
$retries--
if ($retries -lt 0)
{
throw $_
}
Write-Warning "Retrying"
Start-Sleep -Seconds 10
}
}
# Checking automation account identity access
Write-Host "Checking automation account identity access" -ForegroundColor $CommandInfo
$AcIdentity = Get-AzADServicePrincipal -DisplayName $AutomationAccountName
if (-Not $AcIdentity)
{
throw "ServicePrincipal with name '$($AutomationAccountName)' not found"
}
$GraphApp = Get-MgBetaServicePrincipal -Filter "DisplayName eq 'Microsoft Graph'" -Property "*"
$AppRole = $GraphApp.AppRoles | Where-Object {$_.Value -eq "Mail.Send" -and $_.AllowedMemberTypes -contains "Application"}
$Assignments = Get-MgBetaServicePrincipalAppRoleAssignment -ServicePrincipalId $AcIdentity.Id -All
if ($null -eq ($Assignments | Where-Object {$_.AppRoleId -eq $AppRole.Id -and $_.ResourceId -eq $GraphApp.Id}))
{
New-MgBetaServicePrincipalAppRoleAssignment -ServicePrincipalId $AcIdentity.Id -PrincipalId $AcIdentity.Id -ResourceId $GraphApp.Id -AppRoleId $AppRole.Id
}
$AppRole = $GraphApp.AppRoles | Where-Object {$_.Value -eq "Application.ReadWrite.OwnedBy" -and $_.AllowedMemberTypes -contains "Application"}
if ($null -eq ($Assignments | Where-Object {$_.AppRoleId -eq $AppRole.Id -and $_.ResourceId -eq $GraphApp.Id}))
{
New-MgBetaServicePrincipalAppRoleAssignment -ServicePrincipalId $AcIdentity.Id -PrincipalId $AcIdentity.Id -ResourceId $GraphApp.Id -AppRoleId $AppRole.Id
}
$AutomationAccountId = "/subscriptions/$($AutomationAccount.SubscriptionId)/resourceGroups/$($AutomationAccount.ResourceGroupName)/providers/Microsoft.Automation/automationAccounts/$AutomationAccountName"
$RoleAssignment = Get-AzRoleAssignment -RoleDefinitionName "Contributor" -ObjectId $AcIdentity.Id -Scope $AutomationAccountId -ErrorAction Continue | Where-Object { $_.Scope -eq $AutomationAccountId }
$Retries = 0;
While ($null -eq $RoleAssignment -and $Retries -le 6)
{
$RoleAssignment = New-AzRoleAssignment -RoleDefinitionName "Contributor" -ObjectId $AcIdentity.Id -Scope $AutomationAccountId -ErrorAction Continue
Start-Sleep -s 10
$RoleAssignment = Get-AzRoleAssignment -RoleDefinitionName "Contributor" -ObjectId $AcIdentity.Id -Scope $AutomationAccountId -ErrorAction Continue | Where-Object { $_.Scope -eq $AutomationAccountId }
$Retries++;
}
if ($Retries -gt 6)
{
throw "Was not able to set role assigment 'Contributor' for app $($AcIdentity.Id) on scope $($AutomationAccountId)"
}
# Checking RunAs application
Write-Host "Checking RunAs application" -ForegroundColor $CommandInfo
$RunasAppName = "$($AutomationAccountName)RunAsApp"
$AzAdApplication = Get-AzADApplication -DisplayName $RunasAppName -ErrorAction SilentlyContinue
if (-Not $AzAdApplication)
{
Write-Warning "RunAsApp not found. Creating the RunAsApp $RunasAppName"
#Creating application and service principal
Write-Host "Creating application and service principal"
$KeyId = [Guid]::NewGuid()
$HomePageUrl = "https://management.azure.com/subscriptions/$($Context.Subscription.Id)/resourceGroups/$($ResourceGroupName)/providers/Microsoft.Automation/automationAccounts/$($AutomationAccountName)"
$AzAdApplication = New-AzADApplication -DisplayName $RunasAppName -HomePage $HomePageUrl -IdentifierUris ("http://$AlyaTenantName/$KeyId")
$AzAdServicePrincipal = New-AzADServicePrincipal -ApplicationId $AzAdApplication.AppId
#Create credential
$null = New-AzADAppCredential -ApplicationId $AzAdApplication.AppId -CustomKeyIdentifier $CerThumbprint -CertValue $CerKeyValue -StartDate $CerStartDate -EndDate $CerEndDate
#Setting identity as owner (required for automated cert updates)
Write-Host "Setting identity as owner"
$retries = 10
while ($true)
{
try {
$owner = Get-MgBetaApplicationOwner -ApplicationId $AzAdApplication.Id -All | Where-Object { $_.Id -eq $AcIdentity.Id}
break
}
catch {
$retries--
if ($retries -lt 0)
{
throw $_
}
Write-Warning "Waiting for application"
Start-Sleep -Seconds 3
}
}
if ($null -eq $owner)
{
$params = @{
"@odata.id" = "$AlyaGraphEndpoint/beta/directoryObjects/{$($AcIdentity.Id)}"
}
New-MgBetaApplicationOwnerByRef -ApplicationId $AzAdApplication.Id -BodyParameter $params
}
#Granting permissions
Write-Host "Granting permissions"
$SpApp = Get-MgBetaServicePrincipal -Filter "DisplayName eq 'Office 365 SharePoint Online'" -Property "*"
$SpAppRoleSite = $SpApp.AppRoles | Where-Object {$_.Value -eq "Sites.FullControl.All" -and $_.AllowedMemberTypes -contains "Application"}
$SpAppRoleUser = $SpApp.AppRoles | Where-Object {$_.Value -eq "User.Read.All" -and $_.AllowedMemberTypes -contains "Application"}
$GraphAppRoleReadAll = $GraphApp.AppRoles | Where-Object {$_.Value -eq "Directory.Read.All" -and $_.AllowedMemberTypes -contains "Application"}
$GraphAppRoleGroupMemberReadWriteAll = $GraphApp.AppRoles | Where-Object {$_.Value -eq "GroupMember.ReadWrite.All" -and $_.AllowedMemberTypes -contains "Application"}
$params = @{
RequiredResourceAccess = @(
@{
ResourceAppId = "$($SpApp.AppId)"
ResourceAccess = @(
@{
Id = "$($SpAppRoleSite.Id)"
Type = "Role"
},
@{
Id = "$($SpAppRoleUser.Id)"
Type = "Role"
}
)
},
@{
ResourceAppId = "$($GraphApp.AppId)"
ResourceAccess = @(
@{
Id = "$($GraphAppRoleReadAll.Id)"
Type = "Role"
}
)
}
)
}
if ($DeployGroupUpdater)
{
$params = @{
RequiredResourceAccess = @(
@{
ResourceAppId = "$($SpApp.AppId)"
ResourceAccess = @(
@{
Id = "$($SpAppRoleSite.Id)"
Type = "Role"
},
@{
Id = "$($SpAppRoleUser.Id)"
Type = "Role"
}
)
},
@{
ResourceAppId = "$($GraphApp.AppId)"
ResourceAccess = @(
@{
Id = "$($GraphAppRoleReadAll.Id)"
Type = "Role"
},
@{
Id = "$($GraphAppRoleGroupMemberReadWriteAll.Id)"
Type = "Role"
}
)
}
)
}
}
Update-MgBetaApplication -ApplicationId $AzAdApplication.Id -BodyParameter $params
# Waiting for admin consent
$tmp = Get-MgBetaApplication -ApplicationId $AzAdApplication.Id -Property "RequiredResourceAccess"
while ($tmp.RequiredResourceAccess.Count -lt 2)
{
Start-Sleep -Seconds 10
$tmp = Get-MgBetaApplication -ApplicationId $AzAdApplication.Id -Property "RequiredResourceAccess"
}
Start-Sleep -Seconds 60 # Looks like there is some time issue for admin consent #TODO 60 seconds enough
#Admin consent
Write-Host "Setting principal admin consent" -ForegroundColor $CommandInfo
$servicePrincipalId = $AzAdServicePrincipal.Id
foreach($resourceAccess in $params.RequiredResourceAccess)
{
$appId = $resourceAccess.ResourceAppId
$app = Get-MgBetaServicePrincipal -Filter "AppId eq '$appId'" -Property "*"
$perms = $resourceAccess.ResourceAccess
$scopes = ($app.PublishedPermissionScopes | Where-Object { $_.Id -in $perms.Id }).Value -join " "
if ($scopes -and @($scopes).Count -gt 0)
{
try {
New-MgBetaOauth2PermissionGrant -ClientId $servicePrincipalId -ConsentType "AllPrincipals" -ResourceId $app.Id -Scope $scopes -ExpiryTime ([DateTime]::MaxValue)
}
catch {
Write-Error $_.Exception -ErrorAction Continue
Write-Warning "Principal admin consent was not working. Please check in portal if principal admin consent was given to application '$servicePrincipalId'!"
}
}
foreach($perm in ($perms | Where-Object { $_.Type -eq "Role" }))
{
$extAss = Get-MgBetaServicePrincipalAppRoleAssignment -ServicePrincipalId $servicePrincipalId -All | Where-Object { $_.ResourceId -eq $app.Id -and $_.AppRoleId -eq $perm.Id }
if (-Not $extAss)
{
try {
New-MgBetaServicePrincipalAppRoleAssignment -ServicePrincipalId $servicePrincipalId -PrincipalId $servicePrincipalId -ResourceId $app.Id -AppRoleId $perm.Id
}
catch {
Write-Error $_.Exception -ErrorAction Continue
Write-Warning "Principal admin consent was not working. Please check in portal if principal admin consent was given to application '$servicePrincipalId'!"
}
}
}
}
}
else
{
$AzAdServicePrincipal = Get-AzADServicePrincipal -DisplayName $RunasAppName | Where-Object { $_.AppId -eq $AzAdApplication.AppId }
}
# Checking application credential
Write-Host "Checking application credential" -ForegroundColor $CommandInfo
$AppCredential = Get-AzADAppCredential -ApplicationId $AzAdApplication.AppId -ErrorAction SilentlyContinue
if (-Not $AppCredential)
{
Write-Host " Not found" -ForegroundColor $CommandWarning
$AppCredential = New-AzADAppCredential -ApplicationId $AzAdApplication.AppId -CustomKeyIdentifier $CerThumbprint -CertValue $CerKeyValue -StartDate $CerStartDate -EndDate $CerEndDate
}
else
{
if ([System.Convert]::ToBase64String($AppCredential.CustomKeyIdentifier) -ne $CerThumbprint)
{
Write-Host " Updating"
Remove-AzADAppCredential -ObjectId $AzAdApplication.Id -KeyId $AppCredential.KeyId
$AppCredential = New-AzADAppCredential -ApplicationId $AzAdApplication.AppId -CustomKeyIdentifier $CerThumbprint -CertValue $CerKeyValue -StartDate $CerStartDate -EndDate $CerEndDate
}
}
# Checking automation certificate asset
Write-Host "Checking automation certificate asset" -ForegroundColor $CommandInfo
$AutomationCertificate = Get-AzAutomationCertificate -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name $AzureCertifcateAssetName -ErrorAction SilentlyContinue
$CerPassword = ConvertTo-SecureString $PfxCertPlainPasswordForRunAsAccount -AsPlainText -Force
if (-Not $AutomationCertificate)
{
Write-Warning "Automation Certificate not found. Creating the Automation Certificate $AzureCertifcateAssetName"
New-AzAutomationCertificate -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name $AzureCertifcateAssetName -Path $PfxCertPathForRunAsAccount -Password $CerPassword -Exportable:$true
}
else
{
if ($AutomationCertificate.Thumbprint -ne $CerThumbprintString)
{
Write-Host " Updating"
Set-AzAutomationCertificate -ResourceGroupName $ResourceGroupName `
-AutomationAccountName $AutomationAccountName -Name $AzureCertifcateAssetName `
-Path $PfxCertPathForRunAsAccount -Password $CerPassword -Exportable:$true
}
}
#Remove-AzAutomationCertificate -ResourceGroupName -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name $AzureCertificateName -ErrorAction SilentlyContinue
}
finally
{
#Removing exported certificate
Remove-Item -Path $PfxCertPathForRunAsAccount -Force -ErrorAction SilentlyContinue | Out-Null
}
# Checking own management group access
Write-Host "Checking own management group access" -ForegroundColor $CommandInfo
$mgrp = $null
try {
$mgrps = Get-AzManagementGroup
$mgrp = $mgrps[0]
if ($mgrps.Count -gt 1)
{
$mgrp = Select-Item -list $mgrps -message "Please select the root mangement group"
}
$user = Get-CurrentAzAdPrincipal
$RoleAssignment = Get-AzRoleAssignment -ObjectId $user.Id -Scope $mgrp.Id -RoleDefinitionName "Management Group Contributor" -ErrorAction Continue | Where-Object { $_.Scope -eq $mgrp.Id }
$Retries = 0;
While ($null -eq $RoleAssignment -and $Retries -le 6)
{
$RoleAssignment = New-AzRoleAssignment -ObjectId $user.Id -Scope $mgrp.Id -RoleDefinitionName "Management Group Contributor" -ErrorAction Continue
Start-Sleep -Seconds 10
$RoleAssignment = Get-AzRoleAssignment -ObjectId $user.Id -Scope $mgrp.Id -RoleDefinitionName "Management Group Contributor" -ErrorAction Continue | Where-Object { $_.Scope -eq $mgrp.Id }
$Retries++;
}
if ($Retries -gt 6)
{
throw "Was not able to set role assigment 'Management Group Contributor' for user $($user.Id) on scope $($mgrp.Id)"
}
$RoleAssignment = Get-AzRoleAssignment -ObjectId $user.Id -Scope $mgrp.Id -RoleDefinitionName "User Access Administrator" -ErrorAction Continue | Where-Object { $_.Scope -eq $mgrp.Id }
$Retries = 0;
While ($null -eq $RoleAssignment -and $Retries -le 6)
{
$RoleAssignment = New-AzRoleAssignment -ObjectId $user.Id -Scope $mgrp.Id -RoleDefinitionName "User Access Administrator" -ErrorAction Continue
Start-Sleep -Seconds 10
$RoleAssignment = Get-AzRoleAssignment -ObjectId $user.Id -Scope $mgrp.Id -RoleDefinitionName "User Access Administrator" -ErrorAction Continue | Where-Object { $_.Scope -eq $mgrp.Id }
$Retries++;
}
if ($Retries -gt 6)
{
throw "Was not able to set role assigment 'User Access Administrator' for user $($user.Id) on scope $($mgrp.Id)"
}
}
catch {
Write-Warning "You need access to the root mangement group!"
Write-Warning "Please go to https://portal.azure.com/?feature.msaljs=true#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/Properties"
Write-Warning "and enable 'Access management for Azure resources'"
Write-Warning "Also go to https://portal.azure.com/?feature.msaljs=true#view/Microsoft_Azure_ManagementGroups/ManagementGroupBrowseBlade/~/MGBrowse_overview"
Write-Warning "and press 'Start using management groups'"
Write-Warning "Restart this script"
pause
exit
}
# Checking app management group access
Write-Host "Checking app management group access" -ForegroundColor $CommandInfo
$RoleAssignment = Get-AzRoleAssignment -RoleDefinitionName "Contributor" -ObjectId $AzAdServicePrincipal.Id -Scope $mgrp.Id -ErrorAction Continue | Where-Object { $_.Scope -eq $mgrp.Id }
$Retries = 0;
While ($null -eq $RoleAssignment -and $Retries -le 6)
{
$RoleAssignment = New-AzRoleAssignment -RoleDefinitionName "Contributor" -ObjectId $AzAdServicePrincipal.Id -Scope $mgrp.Id -ErrorAction Continue
Start-Sleep -Seconds 10
$RoleAssignment = Get-AzRoleAssignment -RoleDefinitionName "Contributor" -ObjectId $AzAdServicePrincipal.Id -Scope $mgrp.Id -ErrorAction Continue | Where-Object { $_.Scope -eq $mgrp.Id }
$Retries++;
}
if ($Retries -gt 6)
{
throw "Was not able to set role assigment Contributor for app $($AzAdServicePrincipal.AppId) on scope $($mgrp.Id)"
}
# Checking app key vault access
Write-Host "Checking app key vault access" -ForegroundColor $CommandInfo
if ($KeyVault.EnableRbacAuthorization)
{
$RoleAssignment = Get-AzRoleAssignment -RoleDefinitionName "Key Vault Secrets User" -ObjectId $AzAdServicePrincipal.Id -Scope $KeyVault.ResourceId -ErrorAction Continue | Where-Object { $_.Scope -eq $KeyVault.ResourceId }
$Retries = 0;
While ($null -eq $RoleAssignment -and $Retries -le 6)
{
$RoleAssignment = New-AzRoleAssignment -RoleDefinitionName "Key Vault Secrets User" -ObjectId $AzAdServicePrincipal.Id -Scope $KeyVault.ResourceId -ErrorAction Continue
Start-Sleep -s 10
$RoleAssignment = Get-AzRoleAssignment -RoleDefinitionName "Key Vault Secrets User" -ObjectId $AzAdServicePrincipal.Id -Scope $KeyVault.ResourceId -ErrorAction Continue | Where-Object { $_.Scope -eq $KeyVault.ResourceId }
$Retries++;
}
if ($Retries -gt 6)
{
throw "Was not able to set role assigment 'Key Vault Secrets User' for app $($AzAdServicePrincipal.AppId) on scope $($KeyVault.ResourceId)"
}
$RoleAssignment = Get-AzRoleAssignment -RoleDefinitionName "Key Vault Certificate User" -ObjectId $AzAdServicePrincipal.Id -Scope $KeyVault.ResourceId -ErrorAction Continue | Where-Object { $_.Scope -eq $KeyVault.ResourceId }
$Retries = 0;
While ($null -eq $RoleAssignment -and $Retries -le 6)
{
$RoleAssignment = New-AzRoleAssignment -RoleDefinitionName "Key Vault Certificate User" -ObjectId $AzAdServicePrincipal.Id -Scope $KeyVault.ResourceId -ErrorAction Continue
Start-Sleep -s 10
$RoleAssignment = Get-AzRoleAssignment -RoleDefinitionName "Key Vault Certificate User" -ObjectId $AzAdServicePrincipal.Id -Scope $KeyVault.ResourceId -ErrorAction Continue | Where-Object { $_.Scope -eq $KeyVault.ResourceId }
$Retries++;
}
if ($Retries -gt 6)
{
throw "Was not able to set role assigment 'Key Vault Certificate User' for app $($AzAdServicePrincipal.AppId) on scope $($KeyVault.ResourceId)"
}
}
else
{
Set-AzKeyVaultAccessPolicy -VaultName $KeyVaultName -ObjectId $AzAdServicePrincipal.Id -PermissionsToCertificates "Get" -PermissionsToSecrets "Get" -ErrorAction Continue
}
# Checking if AVD is enabled
$AvdEnabled = $false
if ($AlyaAvdDomainAdminUPN)
{
$AvdEnabled = $true
#TODO RunAsApp access to AVD resources and user messaging!
}
# Checking PreparePs7RuntimeEnv
if ($PreparePs7RuntimeEnv)
{
Write-Host "Checking runtime environments in Automation Account" -ForegroundColor $CommandInfo
Write-Host " Please enable now runtime environments in Automation Account"
pause
& "$AlyaScripts\automation\Create-RuntimeEnvironment.ps1"
& "$AlyaScripts\automation\Install-RuntimeEnvironmentPackages.ps1"
& "$AlyaScripts\automation\Update-RuntimeEnvironmentPackages.ps1"
$reqUrl = "$($AutomationAccountId)/runtimeEnvironments?api-version=2024-10-23"
$retries = 10
do {
try {
$resp = Invoke-AzRestMethod -Method Get -Path $reqUrl
if ($resp.StatusCode -ge 400)
{
throw "Error getting runtime environments: $($resp.Content)"
}
break
}
catch {
Write-Warning "Error getting runtime environments, retrying in 10 seconds..."
}
$retries--
if ($retries -le 0) {
throw "Failed to get runtime environments after multiple retries"
}
Start-Sleep -Seconds 10
} while ($true)
$runEnvs = $resp.Content | ConvertFrom-Json
$runEnvs = $runEnvs.value | Where-Object { $_.properties.runtime.language -eq "PowerShell" }
if (-Not $runEnvs)
{
throw "Can't get runtime environments"
}
$runtimeEnvironment = @(($runEnvs | Where-Object { $_.properties.description -notlike "System-generated*" -and $_.properties.description -like "*PowerShell*" }).Name | Sort-Object -Descending)[0]
}
if ($DeploySharePointRunAsApp)
{
$spSecData = & "$AlyaScripts\sharepoint\Configure-ServiceApplication.ps1" -ForAutomationAccount $true -PassThrough $true
Write-Host "Checking SharePointRunAs application" -ForegroundColor $CommandInfo
$AzAdApplication = Get-AzADApplication -ApplicationId $spSecData.ClientId
if (-Not $AzAdApplication)
{
throw "SharePointRunAsApp not found."
}
#Setting identity as owner (required for automated cert updates)
Write-Host "Setting identity as owner"
$retries = 10
while ($true)
{
try {
$owner = Get-MgBetaApplicationOwner -ApplicationId $AzAdApplication.Id -All | Where-Object { $_.Id -eq $AcIdentity.Id}
break
}
catch {
$retries--
if ($retries -lt 0)
{
throw $_
}
Write-Warning "Waiting for application"
Start-Sleep -Seconds 3
}
}
if ($null -eq $owner)
{
$params = @{
"@odata.id" = "$AlyaGraphEndpoint/beta/directoryObjects/{$($AcIdentity.Id)}"
}
New-MgBetaApplicationOwnerByRef -ApplicationId $AzAdApplication.Id -BodyParameter $params
}
}
# Publish runbooks
if (-Not (Test-Path "$SolutionDataRoot\$($AutomationAccountName)"))
{
New-Item -Path "$SolutionDataRoot\$($AutomationAccountName)" -ItemType Directory -Force
}
if ($PreparePs5Runbooks)
{
Write-Host "Checking automation runbook 01" -ForegroundColor $CommandInfo
$runbookPath = "$SolutionDataRoot\$($AutomationAccountName)\$($AutomationAccountName)rb01.ps1"
if (-Not (Test-Path $runbookPath) -or $UpdateRunbooks)
{
$rbContent = Get-Content -Path "$SolutionScriptsRoot\runbook01.ps1" -Raw -Encoding $AlyaUtf8Encoding
$rbContent = $rbContent.Replace("##AlyaAzureEnvironment##", $AlyaAzureEnvironment)
$rbContent = $rbContent.Replace("##AlyaResourceGroupName##", $ResourceGroupName)
$rbContent = $rbContent.Replace("##AlyaAutomationAccountName##", $AutomationAccountName)
$rbContent = $rbContent.Replace("##AlyaRunbookName##", ($AutomationAccountName+"rb01"))
$rbContent = $rbContent.Replace("##AlyaApplicationId##", $AzAdApplication.AppId)
$rbContent = $rbContent.Replace("##AlyaTenantId##", $Context.Tenant.Id)
$rbContent = $rbContent.Replace("##AlyaCertificateKeyVaultName##", $keyVaultName)
$rbContent = $rbContent.Replace("##AlyaCertificateSecretName##", $AzureCertificateName)
$rbContent = $rbContent.Replace("##AlyaSubscriptionId##", $Context.Subscription.Id)
$rbContent = $rbContent.Replace("##AlyaSubscriptionIds##", $AlyaSubscriptionIds)
$rbContent = $rbContent.Replace("##AlyaTimeZone##", $AlyaTimeZone)
$rbContent = $rbContent.Replace("##AlyaFromMail##", "DoNotReply@$($AlyaDomainName)")
$rbContent = $rbContent.Replace("##AlyaToMail##", $AlyaSupportEmail)
$rbContent = $rbContent.Replace("##AlyaAllExternalsGroup##", $AlyaAllExternals)
$rbContent = $rbContent.Replace("##AlyaAllInternalsGroup##", $AlyaAllInternals)
$rbContent = $rbContent.Replace("##AlyaGraphEndpoint##", $AlyaGraphEndpoint)
$rbContent = $rbContent.Replace("##AlyaCertifcateAssetName##", $AzureCertifcateAssetName)
$rbContent | Set-Content -Path $runbookPath -Force -Encoding UTF8
}
$Runnbook = Get-AzAutomationRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name ($AutomationAccountName+"rb01") -ErrorAction SilentlyContinue
if (-Not $Runnbook)
{
Write-Warning "Automation Runbook 01 not found. Creating the Automation Runbook $($AutomationAccountName+"rb01")"
if (-Not (Test-Path $runbookPath))
{
Write-Error "Can't find runbook $($runbookPath)" -ErrorAction Continue
Exit 2
}
$null = Import-AzAutomationRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name ($AutomationAccountName+"rb01") -Type PowerShell -Description "Updates the Azure modules in the automation account" -Tags @{displayName="Module Updater"} -Path $runbookPath -Force
$null = Publish-AzAutomationRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name ($AutomationAccountName+"rb01")
$Schedule = Get-AzAutomationSchedule -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name "Monthly2AM" -ErrorAction SilentlyContinue
if (-Not $Schedule)
{
$Schedule = New-AzAutomationSchedule -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name "Monthly2AM" -StartTime ((Get-Date "02:00:00").AddDays(1)) -MonthInterval 1 -DayOfWeek Saturday -DayOfWeekOccurrence First -TimeZone ([System.TimeZoneInfo]::Local).Id
}
$null = Register-AzAutomationScheduledRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -RunbookName ($AutomationAccountName+"rb01") -ScheduleName "Monthly2AM"
}
else
{
if ($UpdateRunbooks)
{
Write-Host "Automation Runbook 01 found. Updating the Automation Runbook $($AutomationAccountName+"rb01")"
$null = Import-AzAutomationRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name ($AutomationAccountName+"rb01") -Type PowerShell -Description "Updates the Azure modules in the automation account" -Tags @{displayName="Module Updater"} -Path $runbookPath -Force
$null = Publish-AzAutomationRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name ($AutomationAccountName+"rb01")
}
}
Write-Host "Checking automation runbook 02" -ForegroundColor $CommandInfo
$runbookPath = "$SolutionDataRoot\$($AutomationAccountName)\$($AutomationAccountName)rb02.ps1"
if (-Not (Test-Path $runbookPath) -or $UpdateRunbooks)
{
$rbContent = Get-Content -Path "$SolutionScriptsRoot\runbook02.ps1" -Raw -Encoding $AlyaUtf8Encoding
$modules = "@{Name=`"Az.Accounts`"; Version=`$null}, @{Name=`"Az.Automation`"; Version=`$null}, @{Name=`"Az.Storage`"; Version=`$null}, @{Name=`"Az.Compute`"; Version=`$null}, @{Name=`"Az.Resources`"; Version=`$null}, @{Name=`"Az.KeyVault`"; Version=`$null}"
if ($AvdEnabled) { $modules += ", @{Name=`"Az.DesktopVirtualization`"; Version=`$null}" }
$rbContent = $rbContent.Replace("##AlyaModules##", $modules)
$rbContent = $rbContent.Replace("##AlyaAzureEnvironment##", $AlyaAzureEnvironment)
$rbContent = $rbContent.Replace("##AlyaResourceGroupName##", $ResourceGroupName)
$rbContent = $rbContent.Replace("##AlyaAutomationAccountName##", $AutomationAccountName)
$rbContent = $rbContent.Replace("##AlyaRunbookName##", ($AutomationAccountName+"rb02"))
$rbContent = $rbContent.Replace("##AlyaApplicationId##", $AzAdApplication.AppId)
$rbContent = $rbContent.Replace("##AlyaTenantId##", $Context.Tenant.Id)
$rbContent = $rbContent.Replace("##AlyaCertificateKeyVaultName##", $keyVaultName)
$rbContent = $rbContent.Replace("##AlyaCertificateSecretName##", $AzureCertificateName)
$rbContent = $rbContent.Replace("##AlyaSubscriptionId##", $Context.Subscription.Id)
$rbContent = $rbContent.Replace("##AlyaSubscriptionIds##", $AlyaSubscriptionIds)
$rbContent = $rbContent.Replace("##AlyaTimeZone##", $AlyaTimeZone)
$rbContent = $rbContent.Replace("##AlyaFromMail##", "DoNotReply@$($AlyaDomainName)")
$rbContent = $rbContent.Replace("##AlyaToMail##", $AlyaSupportEmail)
$rbContent = $rbContent.Replace("##AlyaAllExternalsGroup##", $AlyaAllExternals)
$rbContent = $rbContent.Replace("##AlyaAllInternalsGroup##", $AlyaAllInternals)
$rbContent = $rbContent.Replace("##AlyaGraphEndpoint##", $AlyaGraphEndpoint)
$rbContent = $rbContent.Replace("##AlyaCertifcateAssetName##", $AzureCertifcateAssetName)
$rbContent | Set-Content -Path $runbookPath -Force -Encoding UTF8
}
$Runnbook = Get-AzAutomationRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name ($AutomationAccountName+"rb02") -ErrorAction SilentlyContinue
if (-Not $Runnbook)
{
Write-Warning "Automation Runbook 02 not found. Creating the Automation Runbook $($AutomationAccountName+"rb02")"
if (-Not (Test-Path $runbookPath))
{
Write-Error "Can't find runbook $($runbookPath)" -ErrorAction Continue
Exit 3
}
$null = Import-AzAutomationRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name ($AutomationAccountName+"rb02") -Type PowerShell -Description "Installs required modules in the automation account" -Tags @{displayName="Module Installer"} -Path $runbookPath -Force
$null = Publish-AzAutomationRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name ($AutomationAccountName+"rb02")
$Schedule = Get-AzAutomationSchedule -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name "Monthly3AM" -ErrorAction SilentlyContinue
if (-Not $Schedule)
{
$Schedule = New-AzAutomationSchedule -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name "Monthly3AM" -StartTime ((Get-Date "03:00:00").AddDays(1)) -MonthInterval 1 -DayOfWeek Saturday -DayOfWeekOccurrence First -TimeZone ([System.TimeZoneInfo]::Local).Id
}
$null = Register-AzAutomationScheduledRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -RunbookName ($AutomationAccountName+"rb02") -ScheduleName "Monthly3AM"
}
else
{
if ($UpdateRunbooks)
{
Write-Host "Automation Runbook 02 found. Updating the Automation Runbook $($AutomationAccountName+"rb02")"
$null = Import-AzAutomationRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name ($AutomationAccountName+"rb02") -Type PowerShell -Description "Installs required modules in the automation account" -Tags @{displayName="Module Installer"} -Path $runbookPath -Force
$null = Publish-AzAutomationRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name ($AutomationAccountName+"rb02")
}
}
}
Write-Host "Checking automation runbook 03" -ForegroundColor $CommandInfo
$runbookPath = "$SolutionDataRoot\$($AutomationAccountName)\$($AutomationAccountName)rb03.ps1"
if (-Not (Test-Path $runbookPath) -or $UpdateRunbooks)
{
$rbContent = Get-Content -Path "$SolutionScriptsRoot\runbook03.ps1" -Raw -Encoding $AlyaUtf8Encoding
$rbContent = $rbContent.Replace("##AlyaAzureEnvironment##", $AlyaAzureEnvironment)
$rbContent = $rbContent.Replace("##AlyaResourceGroupName##", $ResourceGroupName)
$rbContent = $rbContent.Replace("##AlyaAutomationAccountName##", $AutomationAccountName)
$rbContent = $rbContent.Replace("##AlyaRunbookName##", ($AutomationAccountName+"rb03"))
$rbContent = $rbContent.Replace("##AlyaApplicationId##", $AzAdApplication.AppId)
$rbContent = $rbContent.Replace("##AlyaTenantId##", $Context.Tenant.Id)
$rbContent = $rbContent.Replace("##AlyaCertificateKeyVaultName##", $keyVaultName)
$rbContent = $rbContent.Replace("##AlyaCertificateSecretName##", $AzureCertificateName)
$rbContent = $rbContent.Replace("##AlyaSubscriptionId##", $Context.Subscription.Id)
$rbContent = $rbContent.Replace("##AlyaSubscriptionIds##", $AlyaSubscriptionIds)
$rbContent = $rbContent.Replace("##AlyaTimeZone##", $AlyaTimeZone)
$rbContent = $rbContent.Replace("##AlyaFromMail##", "DoNotReply@$($AlyaDomainName)")