-
Notifications
You must be signed in to change notification settings - Fork 1
/
Deploy-SubscriptionManagementSolution.ps1
5732 lines (5042 loc) · 245 KB
/
Deploy-SubscriptionManagementSolution.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Deploy Subscription Management Solution Script
.DESCRIPTION
This script will deploy the Subscription Management Solution to the selected Subscription.
.PARAMETER ResourceGroupName
Define a name for the Resource Group to be used. It can be a new or exisiting Resource Group
Example: "Subscription-Management-RG"
.PARAMETER AutomationAccountNamePrefix
Define the prefix for the Automation Account Name.
Maximum of 37 characters
Example: "Subscription-Mgmt-Automation-Account-"
.PARAMETER KeyVaultNamePrefix
Define the prefix for the Key Vault Name.
Maximum of 10 characters
Example: "KeyVault-"
.EXAMPLE
.\Deploy-SubscriptionManagementSolution.ps1
#>
[CmdletBinding()]
Param
(
# Define a name for the Resource Group to be used. It can be a new or exisiting Resource Group
# Example: "Subscription-Management-RG"
[parameter(Mandatory=$false,HelpMessage='Example: Subscription-Management-RG')]
[String]$ResourceGroupName = 'Subscription-Management-RG',
# Define the prefix for the Automation Account Name.
# Maximum of 37 characters
# Example: "Subscription-Mgmt-Automation-Account-"
[parameter(Mandatory=$false,HelpMessage='Example: Subscription-Mgmt-Automation-Account-')]
[ValidateLength(1,37)]
[String]$AutomationAccountNamePrefix = 'Subscription-Mgmt-Automation-Account-',
# Define the prefix for the Key Vault Name.
# Maximum of 10 characters
# Example: "KeyVault-"
[parameter(Mandatory=$false,HelpMessage='Example: KeyVault-')]
[ValidateLength(1,10)]
[String]$KeyVaultNamePrefix = 'KeyVault-'
)
# Set verbose preference
$VerbosePreference = 'Continue'
#region Enviornment Selection
$Environments = Get-AzureRmEnvironment
$Environment = $Environments | Out-GridView -Title "Please Select an Azure Enviornment." -PassThru
#endregion
#region Connect to Azure
try
{
$AzureRMAccount = Connect-AzureRmAccount -Environment $($Environment.Name) -ErrorAction 'Stop'
}
catch
{
Write-Error -Message $_.Exception
break
}
try
{
$Subscriptions = Get-AzureRmSubscription
if ($Subscriptions.Count -gt '1')
{
$Subscription = $Subscriptions | Out-GridView -Title "Please Select a Subscription." -PassThru
Select-AzureRmSubscription $Subscription
$SubscriptionID = $Subscription.SubscriptionID
$TenantID = $Subscription.TenantId
}
else
{
$SubscriptionID = $Subscriptions.SubscriptionID
$TenantID = $Subscriptions.TenantId
}
}
catch
{
Write-Error -Message $_.Exception
break
}
#endregion
#region Location Selection
$Locations = Get-AzureRmLocation
$Location = ($Locations | Out-GridView -Title "Please Select a location." -PassThru).Location
#endregion
#region Set Script Variables
# External IP Information
$ExternalIP = Invoke-RestMethod -Uri 'http://ipinfo.io/json' | Select-Object -ExpandProperty IP
# Enviornment
$AuthorityURL = $($AzureRMAccount.Context.Environment.ActiveDirectoryAuthority)
$ResourceManagerUrl = $($AzureRMAccount.Context.Environment.ResourceManagerUrl)
$TokenAuthority = $AuthorityURL + $TenantID + '/'
$ResourceManagerUrl = $($Environment.ResourceManagerUrl)
$ResourceURL = $($Environment.ServiceManagementUrl)
# Automation Account
$AutomationAccountName = $AutomationAccountNamePrefix + ($SubscriptionID.substring(0,13)).ToUpper()
# Key Vault
$KeyVaultName = $KeyVaultNamePrefix + ($SubscriptionID.substring(0,13)).ToUpper()
# Storage Account
$StorageAccountName = 'sharedsa' + ($SubscriptionID.Replace('-','').substring(0,13)).ToLower()
$StorageAccountType = 'Standard_GRS'
$StorageKind = 'StorageV2'
$StorageAccessTier = 'Hot'
$AdminScriptsContainerName = 'administrationscripts'
$WindowsUpdateScriptsFolderName = 'WindowsUpdateScripts'
$ReportsFolderName = 'Reports'
$SubscriptionReportsContainerName = 'subscriptionreports'
#endregion
#region Create Custom Role Definitions
#region Create Virtual Machine Extension Operator Custom Role
$VirtualMachineExtensionOperatorCustomRoleName = "Virtual Machine Extension Operator for Subscription $SubscriptionID"
$CustomRoleDescription = "Can deploy Extensions to virtual machines in Subscription $SubscriptionID"
$CustomRole = Get-AzureRmRoleDefinition -Name $VirtualMachineExtensionOperatorCustomRoleName
if (!$CustomRole)
{
Write-Output "Creating $VirtualMachineExtensionOperatorCustomRoleName Custom Role"
$Permissions = @(
'Microsoft.Compute/virtualMachines/extensions/read',
'Microsoft.Compute/virtualMachines/extensions/delete',
'Microsoft.Compute/virtualMachines/extensions/write'
)
$NewRole = [Microsoft.Azure.Commands.Resources.Models.Authorization.PSRoleDefinition]::new()
$NewRole.Name = $VirtualMachineExtensionOperatorCustomRoleName
$NewRole.Description = $CustomRoleDescription
$NewRole.IsCustom = $true
$NewRole.Actions = $Permissions
$Subscription = '/subscriptions/' + $SubscriptionID
$NewRole.AssignableScopes = $Subscription
New-AzureRmRoleDefinition -Role $NewRole -Verbose -ErrorAction 'Stop'
}
#endregion
#region Create Service Endpoint Manager Custom Role
$ServiceEndpointManagerCutomRoleName = "Service Endpoint Manager for Subscription $SubscriptionID"
$CustomRoleDescription = "Can manage Service Endpoints and Endpoint Policies in Subscription $SubscriptionID"
$CustomRole = Get-AzureRmRoleDefinition -Name $ServiceEndpointManagerCutomRoleName
if (!$CustomRole)
{
Write-Output "Creating $ServiceEndpointManagerCutomRoleName Custom Role"
$Permissions = @(
'Microsoft.Network/serviceEndpointPolicies/delete',
'Microsoft.Network/serviceEndpointPolicies/join/action',
'Microsoft.Network/serviceEndpointPolicies/joinSubnet/action',
'Microsoft.Network/locations/virtualNetworkAvailableEndpointServices/read',
'Microsoft.Network/serviceEndpointPolicies/read',
'Microsoft.Network/serviceEndpointPolicies/serviceEndpointPolicyDefinitions/delete',
'Microsoft.Network/serviceEndpointPolicies/serviceEndpointPolicyDefinitions/read',
'Microsoft.Network/serviceEndpointPolicies/serviceEndpointPolicyDefinitions/write',
'Microsoft.Network/serviceEndpointPolicies/write',
'Microsoft.Network/virtualNetworks/subnets/joinViaServiceEndpoint/action',
'Microsoft.Network/virtualNetworks/write'
)
$NewRole = [Microsoft.Azure.Commands.Resources.Models.Authorization.PSRoleDefinition]::new()
$NewRole.Name = $ServiceEndpointManagerCutomRoleName
$NewRole.Description = $CustomRoleDescription
$NewRole.IsCustom = $true
$NewRole.Actions = $Permissions
$Subscription = '/subscriptions/' + $SubscriptionID
$NewRole.AssignableScopes = $Subscription
New-AzureRmRoleDefinition -Role $NewRole -Verbose -ErrorAction 'Stop'
}
#endregion
#endregion
#region Resource Group
# Create the resource group if needed
try
{
Get-AzureRmResourceGroup -Name $ResourceGroupName -ErrorAction 'Stop'
Write-Output "Found Resource Group $ResourceGroupName"
}
catch
{
Write-Output "Creating Resource Group $ResourceGroupName"
New-AzureRmResourceGroup -Name $ResourceGroupName -Location $Location -ErrorAction 'Stop'
}
#endregion
#region KeyVault
Write-Output "Checking for Key Vault $KeyVaultName"
$KeyVaultTest = Get-AzureRmKeyVault -ResourceGroupName $ResourceGroupName | Where-Object {$_.VaultName -eq $KeyVaultName}
if (!$KeyVaultTest)
{
Write-Warning -Message "Key Vault not found. Creating the Key Vault $keyVaultName"
try
{
$KeyVault = New-AzureRmKeyVault -VaultName $keyVaultName -ResourceGroupName $ResourceGroupName -Location $Location -Sku 'Premium' -Verbose -ErrorAction 'Stop'
Write-Output "Key Vault $keyVaultName created successfully"
}
catch
{
if ($Error[0].Exception -like "*LocationNotAvailableForResourceType:*")
{
$Locations = (Get-AzureRmResourceProvider -ProviderNamespace 'Microsoft.KeyVault' | Where-Object {$_.ResourceTypes.ResourceTypeName -eq 'vaults'}).Locations
$NewLocationSelection = $Locations | Out-GridView -Title "The location selected is not valid for Key Vault, please select a new location." -PassThru
$NewLocation = $NewLocationSelection.Replace(' ','').ToLower()
$KeyVault = New-AzureRmKeyVault -VaultName $keyVaultName -ResourceGroupName $ResourceGroupName -Location $NewLocation -Sku 'Premium' -Verbose -ErrorAction 'Stop'
}
else
{
Write-Output $Error[0].Exception
break
}
}
}
try
{
Write-Output 'Setting Key Vault Access Policy'
Set-AzureRmKeyVaultAccessPolicy -ResourceID $KeyVault.ResourceId -EnabledForDeployment -EnabledForTemplateDeployment -EnabledForDiskEncryption -Verbose -ErrorAction 'Stop'
}
catch
{
Write-Warning $_
break
}
Write-Output "Key Vault $KeyVaultName configuration completed successfully"
#endregion
#region Automation Account
Write-Output "Creating Automation Account $AutomationAccountName"
# Create Automation Account
try
{
New-AzureRmAutomationAccount -ResourceGroupName $ResourceGroupName -Name $AutomationAccountName -Location $Location -ErrorAction 'Stop' -Verbose
Write-Output "Automation Account $AutomationAccountName created successfully"
}
catch
{
if ($Error[0].Exception -like "*LocationNotAvailableForResourceType:*")
{
$Locations = (Get-AzureRmResourceProvider -ProviderNamespace 'Microsoft.Automation' | Where-Object {$_.ResourceTypes.ResourceTypeName -eq 'automationAccounts'}).Locations
$NewLocationSelection = $Locations | Out-GridView -Title "The location selected is not valid for Automation Accounts, please select a new location." -PassThru
$NewLocation = $NewLocationSelection.Replace(' ','').ToLower()
New-AzureRmAutomationAccount -ResourceGroupName $ResourceGroupName -Name $AutomationAccountName -Location $NewLocation -Verbose -ErrorAction 'Stop'
}
else
{
Write-Output $Error[0].Exception
break
}
}
$AutomationAccountResourceID = (Get-AzureRmResource -ResourceType Microsoft.Automation/automationAccounts -ResourceGroupName $ResourceGroupName).ResourceId
#endregion
#region Automation Account Certificate
[String] $ApplicationDisplayName = $AutomationAccountName
[String] $SelfSignedCertPlainPassword = [Guid]::NewGuid().ToString().Substring(0, 8) + "!"
[int]$NumberOfMonthsUntilExpired = '36'
$CertifcateAssetName = "AzureRunAsCertificate"
$CertificateName = $AutomationAccountName + $CertifcateAssetName
$PfxCertificatePathForRunAsAccount = Join-Path $env:TEMP ($CertificateName + ".pfx")
$PfxCertificatePlainPasswordForRunAsAccount = $SelfSignedCertPlainPassword
$CerCertificatePathForRunAsAccount = Join-Path $env:TEMP ($CertificateName + ".cer")
$CertificateSubjectName = "cn=" + $CertificateName
# Create Certificate Using Key Vault
Write-Output "Generating the Automation Account Certificate using Key Vault $keyVaultName"
Write-Output 'Creating Key Vault Certificate Policy'
$Policy = New-AzureKeyVaultCertificatePolicy -SecretContentType "application/x-pkcs12" -SubjectName $CertificateSubjectName -IssuerName "Self" -ValidityInMonths $NumberOfMonthsUntilExpired -ReuseKeyOnRenewal
try
{
Write-Output 'Adding Azure Key Vault Certificate'
$AddAzureKeyVaultCertificateStatus = Add-AzureKeyVaultCertificate -VaultName $keyVaultName -Name $CertificateName -CertificatePolicy $Policy -ErrorAction 'Stop'
While ($AddAzureKeyVaultCertificateStatus.Status -eq "inProgress")
{
Start-Sleep -s 10
$AddAzureKeyVaultCertificateStatus = Get-AzureKeyVaultCertificateOperation -VaultName $keyVaultName -Name $CertificateName
}
}
catch
{
Write-Error -Message "Key vault certificate creation was not sucessfull."
break
}
#endregion
#region Create RunAsAccount
# Get Certificate Information from Key Vault
Write-Output "Get Certificate Information from Key Vault $keyVaultName"
$SecretRetrieved = Get-AzureKeyVaultSecret -VaultName $KeyVaultName -Name $CertificateName -ErrorAction 'Stop'
$PfxBytes = [System.Convert]::FromBase64String($SecretRetrieved.SecretValueText)
$CertificateCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$CertificateCollection.Import($PfxBytes, $null, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
# Export the .pfx file
$protectedCertificateBytes = $CertificateCollection.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $PfxCertificatePlainPasswordForRunAsAccount)
[System.IO.File]::WriteAllBytes($PfxCertificatePathForRunAsAccount, $protectedCertificateBytes)
# Export the .cer file
$Certificate = Get-AzureKeyVaultCertificate -VaultName $keyVaultName -Name $CertificateName -ErrorAction 'Stop'
$CertificateBytes = $Certificate.Certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
[System.IO.File]::WriteAllBytes($CerCertificatePathForRunAsAccount, $CertificateBytes)
Write-Output "Creating Service Principal"
# Create Service Principal
$PfxCertificate = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @($PfxCertificatePathForRunAsAccount, $PfxCertificatePlainPasswordForRunAsAccount)
$KeyValue = [System.Convert]::ToBase64String($PfxCertificate.GetRawCertData())
$KeyId = [Guid]::NewGuid()
$StartDate = Get-Date
$EndDate = (Get-Date $PfxCertificate.GetExpirationDateString()).AddDays(-1)
# Use Key credentials and create AAD Application
Write-Output "Creating Azure AD Application"
try
{
$Application = New-AzureRmADApplication -DisplayName $ApplicationDisplayName -HomePage ("http://" + $applicationDisplayName) -IdentifierUris ("http://" + $KeyId) -ErrorAction 'Stop'
New-AzureRmADAppCredential -ApplicationId $Application.ApplicationId -CertValue $KeyValue -StartDate $StartDate -EndDate $EndDate -ErrorAction 'Stop'
New-AzureRMADServicePrincipal -ApplicationId $Application.ApplicationId -ErrorAction 'Stop'
}
catch
{
Write-Warning $_
break
}
# Allow the service principal application to become active
Start-Sleep -s 30
Write-Output "Service Principal created successfully"
# Create the automation certificate asset
Write-Output "Creating Automation Certificate"
$CertificatePassword = ConvertTo-SecureString $PfxCertificatePlainPasswordForRunAsAccount -AsPlainText -Force
try
{
New-AzureRmAutomationCertificate -ResourceGroupName $ResourceGroupName -automationAccountName $AutomationAccountName -Path $PfxCertificatePathForRunAsAccount -Name $CertifcateAssetName -Password $CertificatePassword -Exportable -ErrorAction 'Stop'
}
catch
{
Write-Warning $_
break
}
# Populate the Connection Field Values
$ConnectionTypeName = "AzureServicePrincipal"
$ConnectionAssetName = "AzureRunAsConnection"
$ConnectionFieldValues = @{"ApplicationId" = $($Application.ApplicationId); "TenantId" = $TenantID; "CertificateThumbprint" = $($PfxCertificate.Thumbprint); "SubscriptionId" = $SubscriptionID}
# Create a Automation connection asset named AzureRunAsConnection in the Automation account. This connection uses the service principal.
Write-Output "Creating Automation Connection"
try
{
New-AzureRmAutomationConnection -ResourceGroupName $ResourceGroupName -automationAccountName $AutomationAccountName -Name $ConnectionAssetName -ConnectionTypeName $connectionTypeName -ConnectionFieldValues $connectionFieldValues -ErrorAction 'Stop'
}
catch
{
Write-Warning $_
break
}
Write-Output "Automation Account $AutomationAccountName creation & configuration completed successfully"
#endregion
#region Assign Automation Account Permissions
Write-Output "Assigning permissions to the Automation Account"
# Assign Subscription Reader
Write-Output "Assigning Subscription Reader to the Automation Account"
$NewRole = $null
[Int]$Retries = '0'
While ($NewRole -eq $null -and $Retries -le 6)
{
New-AzureRMRoleAssignment -RoleDefinitionName Reader -ServicePrincipalName $Application.ApplicationId -scope ("/subscriptions/" + $SubscriptionID) -ErrorAction 'SilentlyContinue'
Start-Sleep -s 10
$NewRole = Get-AzureRMRoleAssignment -ServicePrincipalName $Application.ApplicationId -ErrorAction 'SilentlyContinue'
$Retries++;
}
# Assign Key Vault Contributor
Write-Output "Assigning Key Vault Contributor to the Automation Account"
$NewRole = $null
[Int]$Retries = '0'
While ($NewRole -eq $null -and $Retries -le 6)
{
New-AzureRMRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $Application.ApplicationId -scope ($KeyVault.ResourceId) -ErrorAction 'SilentlyContinue'
Start-Sleep -s 10
$NewRole = Get-AzureRMRoleAssignment -ServicePrincipalName $Application.ApplicationId -ErrorAction 'SilentlyContinue'
$Retries++;
}
# Assign Virtual Machine Contributor
Write-Output "Assigning Virtual Machine Contributor to the Automation Account"
$NewRole = $null
[Int]$Retries = '0'
While ($NewRole -eq $null -and $Retries -le 6)
{
New-AzureRMRoleAssignment -RoleDefinitionName 'Virtual Machine Contributor' -ServicePrincipalName $Application.ApplicationId -scope ("/subscriptions/" + $SubscriptionID) -ErrorAction 'SilentlyContinue'
Start-Sleep -s 10
$NewRole = Get-AzureRMRoleAssignment -ServicePrincipalName $Application.ApplicationId -ErrorAction 'SilentlyContinue'
$Retries++;
}
# Assign Virtual Machine Extension Operator
Write-Output "Assigning Virtual Machine Extension Operator to the Automation Account"
$NewRole = $null
[Int]$Retries = '0'
While ($NewRole -eq $null -and $Retries -le 6)
{
New-AzureRMRoleAssignment -RoleDefinitionName $VirtualMachineExtensionOperatorCustomRoleName -ServicePrincipalName $Application.ApplicationId -scope ("/subscriptions/" + $SubscriptionID) -ErrorAction 'SilentlyContinue'
Start-Sleep -s 10
$NewRole = Get-AzureRMRoleAssignment -ServicePrincipalName $Application.ApplicationId -ErrorAction 'SilentlyContinue'
$Retries++;
}
# Assign Service Endpoint Manager
Write-Output "Assigning Service Endpoint Manager to the Automation Account"
$NewRole = $null
[Int]$Retries = '0'
While ($NewRole -eq $null -and $Retries -le 6)
{
New-AzureRMRoleAssignment -RoleDefinitionName $ServiceEndpointManagerCutomRoleName -ServicePrincipalName $Application.ApplicationId -scope ("/subscriptions/" + $SubscriptionID) -ErrorAction 'SilentlyContinue'
Start-Sleep -s 10
$NewRole = Get-AzureRMRoleAssignment -ServicePrincipalName $Application.ApplicationId -ErrorAction 'SilentlyContinue'
$Retries++;
}
# Assign Contributor to Automation Account
Write-Output "Assigning Contributor of the Automation Account to the Automation Account"
$NewRole = $null
[Int]$Retries = '0'
While ($NewRole -eq $null -and $Retries -le 6)
{
New-AzureRMRoleAssignment -RoleDefinitionName 'Contributor' -ServicePrincipalName $Application.ApplicationId -scope $AutomationAccountResourceID -ErrorAction 'SilentlyContinue'
Start-Sleep -s 10
$NewRole = Get-AzureRMRoleAssignment -ServicePrincipalName $Application.ApplicationId -ErrorAction 'SilentlyContinue'
$Retries++;
}
#endregion
#region Install Automation Account Modules
Write-Output "Installing AzureRM.Profile, AzureRM.KeyVault and AzureRM.Network Modules in Automation Account"
$ModuleTemplateFilePath = New-Item -Path "$env:TEMP\ModuleTemplate.json" -ItemType File -Force
$ModuleTemplateData = @"
{
"`$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0",
"parameters": {
"accountName": {
"type": "String"
},
"accountLocation": {
"type": "String"
},
"Level1": {
"type": "Object"
},
"Level0": {
"type": "Object"
}
},
"variables": {},
"resources": [
{
"type": "Microsoft.Automation/automationAccounts/modules",
"name": "[concat(parameters('accountName'), '/', parameters('Level1').Modules[copyIndex()].Name)]",
"apiVersion": "2015-10-31",
"location": "[parameters('accountLocation')]",
"copy": {
"name": "Level1ModulesInstall",
"count": "[length(parameters('Level1').Modules)]",
"mode": "Serial",
"batchSize": 1
},
"tags": {},
"properties": {
"contentLink": {
"uri": "[parameters('Level1').Modules[copyIndex()].Uri]"
}
},
"dependsOn": []
},
{
"type": "Microsoft.Automation/automationAccounts/modules",
"name": "[concat(parameters('accountName'), '/', parameters('Level0').Modules[copyIndex()].Name)]",
"apiVersion": "2015-10-31",
"location": "[parameters('accountLocation')]",
"copy": {
"name": "Level0ModulesInstall",
"count": "[length(parameters('Level0').Modules)]",
"mode": "Serial",
"batchSize": 1
},
"tags": {},
"properties": {
"contentLink": {
"uri": "[parameters('Level0').Modules[copyIndex()].Uri]"
}
},
"dependsOn": [
"Level1ModulesInstall"
]
}
],
"outputs": {}
}
"@
Add-Content -Path $ModuleTemplateFilePath -Value $ModuleTemplateData
$ModuleParametersFilePath = New-Item -Path "$env:TEMP\ModuleParameters.json" -ItemType File -Force
$ModuleParametersData = @"
{
"`$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"accountName": {
"value": "$AutomationAccountName"
},
"accountLocation": {
"value": "$Location"
},
"level1": {
"value": {
"Modules": [
{
"Name": "AzureRM.profile",
"Uri": "https://devopsgallerystorage.blob.core.windows.net:443/packages/azurerm.profile.5.8.3.nupkg"
}
]
}
},
"level0": {
"value": {
"Modules": [
{
"Name": "AzureRM.KeyVault",
"Uri": "https://devopsgallerystorage.blob.core.windows.net:443/packages/azurerm.keyvault.5.2.1.nupkg"
},
{
"Name": "AzureRM.Network",
"Uri": "https://devopsgallerystorage.blob.core.windows.net:443/packages/azurerm.network.6.11.1.nupkg"
}
]
}
}
}
}
"@
Add-Content -Path $ModuleParametersFilePath -Value $ModuleParametersData
try
{
Write-Output "Installing Azure Automation Modules. This may take a few minutes."
New-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName -TemplateFile $($ModuleTemplateFilePath.FullName) -TemplateParameterFile $($ModuleParametersFilePath.FullName) -ErrorAction 'Stop'
Write-Output "Azure Automation Modules installation completed successfully"
}
catch
{
Write-Warning $_
break
}
#endregion
#region Create Schedules
Write-Output "Creating Azure Automation Schedules"
# Create Hourly Schedule
$HourlyScheduleName = 'Every Hour on the Hour'
Write-Output "Creating Automation Schedule Name $HourlyScheduleName"
try
{
New-AzureRmAutomationSchedule -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name $HourlyScheduleName -StartTime ([datetime]::Today).AddDays(1) -HourInterval 1 -Verbose -ErrorAction 'Stop'
}
catch
{
Write-Warning $_
}
# Create Daily Schedule
$DailyScheduleName = 'Every Day Once a Day'
Write-Output "Creating Automation Schedule Name $DailyScheduleName"
try
{
New-AzureRmAutomationSchedule -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name $DailyScheduleName -StartTime ([datetime]::Today).AddDays(1) -DayInterval 1 -Verbose -ErrorAction 'Stop'
}
catch
{
Write-Warning $_
}
Write-Output "Creation of Azure Automation Schedules completed successfully"
#endregion
#region Create Shared Storage Account
Write-Output "Creating Shared Storage Account $StorageAccountName"
# Create JSON Hashtable
$ArrayParameters =
@'
{
"type": "array",
"defaultValue": []
}
'@ | ConvertFrom-Json
# Get all Subnet IDs and add them to an array
Write-Output "Making sure Microsoft.Storage Service Endpoint is on all Virtual Network Subnets"
$SubnetIDs = @()
$VirtualNetworks = Get-AzureRmVirtualNetwork -Verbose -WarningAction 'SilentlyContinue' -ErrorAction 'Stop' | Where-Object {$_.Location -eq $Location}
foreach ($VirtualNetwork in $VirtualNetworks)
{
foreach ($Subnet in $VirtualNetwork.Subnets | Where-Object {$_.Name -ne 'GatewaySubnet'})
{
$VirtualNetworkSubnetConfig = Get-AzureRmVirtualNetworkSubnetConfig -Name $Subnet.Name -VirtualNetwork $VirtualNetwork -Verbose -WarningAction 'SilentlyContinue'
if (!$VirtualNetworkSubnetConfig.ServiceEndpoints.Service)
{
Write-Output "$($Subnet.Name) has no Service Endpoints"
Write-Output "Adding Microsoft.Storage Service Endpoint to $($Subnet.Name) in Virtual Network $($VirtualNetwork.Name)"
Set-AzureRmVirtualNetworkSubnetConfig -Name $Subnet.Name -VirtualNetwork $VirtualNetwork -AddressPrefix $Subnet.AddressPrefix -ServiceEndpoint 'Microsoft.Storage' -WarningAction 'SilentlyContinue' | Set-AzureRmVirtualNetwork -WarningAction 'SilentlyContinue' -Verbose -ErrorAction 'Stop'
}
else
{
if ($VirtualNetworkSubnetConfig.ServiceEndpoints.Service -notcontains 'Microsoft.Storage')
{
Write-Output "$($Subnet.Name) is missing Microsoft.Storage Service Endpoint"
Write-Output "Adding Microsoft.Storage Service Endpoint to $($Subnet.Name) in Virtual Network $($VirtualNetwork.Name)"
$ServiceEnpoints = @('Microsoft.Storage')
$ServiceEnpoints += $VirtualNetworkSubnetConfig.ServiceEndpoints.Service
Set-AzureRmVirtualNetworkSubnetConfig -Name $Subnet.Name -VirtualNetwork $VirtualNetwork -AddressPrefix $Subnet.AddressPrefix -ServiceEndpoint $ServiceEnpoints -WarningAction 'SilentlyContinue' | Set-AzureRmVirtualNetwork -WarningAction 'SilentlyContinue' -Verbose -ErrorAction 'Stop'
}
}
$SubnetIDs += $Subnet.Id
}
}
Write-Output 'Virtual Network Subnet Configuration completed successfully'
# Add each Subnet Id to JSON Hashtable
foreach ($SubnetID in $SubnetIDs)
{
$ArrayParameters.defaultValue += @{id=$SubnetID}
}
# Convert Hashtable to JSON
$SubnetParameters = $ArrayParameters | ConvertTo-Json
# Create JSON File Template
$SharedStorageAccountFilePath = New-Item -Path "$env:TEMP\SharedStorageAccount.json" -ItemType File -Force
$SharedStorageAccountData = @"
{
"`$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"location": {
"type": "string",
"defaultValue": "$Location"
},
"storageAccountName": {
"type": "string",
"defaultValue": "$StorageAccountName"
},
"accountType": {
"type": "string",
"defaultValue": "$StorageAccountType"
},
"kind": {
"type": "string",
"defaultValue": "$StorageKind"
},
"accessTier": {
"type": "string",
"defaultValue": "$StorageAccessTier"
},
"containerName": {
"type": "string",
"defaultValue": "$AdminScriptsContainerName"
},
"supportsHttpsTrafficOnly": {
"type": "bool",
"defaultValue": true
},
"networkAclsBypass": {
"type": "string",
"defaultValue": "AzureServices"
},
"networkAclsDefaultAction": {
"type": "string",
"defaultValue": "Deny"
},
"networkAclsVirtualNetworkRules": $SubnetParameters
},
"variables": {},
"resources": [
{
"name": "[parameters('storageAccountName')]",
"type": "Microsoft.Storage/storageAccounts",
"apiVersion": "2018-02-01",
"location": "[parameters('location')]",
"properties": {
"accessTier": "[parameters('accessTier')]",
"supportsHttpsTrafficOnly": "[parameters('supportsHttpsTrafficOnly')]",
"networkAcls": {
"bypass": "[parameters('networkAclsBypass')]",
"defaultAction": "[parameters('networkAclsDefaultAction')]",
"ipRules": [
{
"value": "$ExternalIP",
"action": "Allow"
}
],
"virtualNetworkRules": "[parameters('networkAclsVirtualNetworkRules')]"
}
},
"dependsOn": [],
"sku": {
"name": "[parameters('accountType')]"
},
"kind": "[parameters('kind')]",
"resources": [
{
"type": "blobServices/containers",
"apiVersion": "2018-03-01-preview",
"name": "[concat('default/', parameters('containerName'))]",
"dependsOn": [
"[parameters('storageAccountName')]"
],
"properties": {
"publicAccess": "None"
}
}
]
}
],
"outputs": {}
}
"@
Add-Content -Path $SharedStorageAccountFilePath -Value $SharedStorageAccountData
try
{
Write-Output "Creating Shared Storage Account. This may take a few minutes."
New-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName -TemplateFile $($SharedStorageAccountFilePath.FullName) -ErrorAction 'Stop'
Write-Output "Creation of Shared Storage Account $StorageAccountName completed successfully"
}
catch
{
Write-Warning $_
break
}
$StorageAccount = Get-AzureRmStorageAccount -ResourceGroupName $ResourceGroupName -Name $StorageAccountName
$BlobServiceEndpoint = $($StorageAccount.PrimaryEndpoints.Blob)
$ContainerURL = $BlobServiceEndpoint + $AdminScriptsContainerName
$WindowsUpdateScriptsFolderURL = $ContainerURL + '/' + $WindowsUpdateScriptsFolderName
# Assign Storage Account Contributor
Write-Output "Assigning Storage Account Contributor to the Automation Account"
$NewRole = $null
[Int]$Retries = '0'
While ($NewRole -eq $null -and $Retries -le 6)
{
New-AzureRMRoleAssignment -RoleDefinitionName Owner -ServicePrincipalName $Application.ApplicationId -scope ($StorageAccount.Id) -ErrorAction 'SilentlyContinue'
Start-Sleep -s 10
$NewRole = Get-AzureRMRoleAssignment -ServicePrincipalName $Application.ApplicationId -ErrorAction 'SilentlyContinue'
$Retries++;
}
Write-Output "Creation and configuration of Shared Storage Account $StorageAccountName completed successfully"
#endregion
#region Upload Windows Update Scripts to Common Storage Account
Write-Output "Uploading Windows Update Scripts to Storage Account $StorageAccountName"
# Upload Invoke-WindowsUpdate.ps1 to Storage Account
Write-Output "Uploading Invoke-WindowsUpdate.ps1 to Storage Account $($StorageAccount.StorageAccountName)"
$WindowsUpdateFilePath = New-Item -Path "$env:TEMP\Invoke-WindowsUpdate.ps1" -ItemType File -Force
$WindowsUpdateFileContent = @'
<#
.SYNOPSIS
Script to Invoke immediate Windows Update Check and Install
.DESCRIPTION
This script was developed to be run as a Custom Script Extension on a Windows Azure Virtual Machine
The script will force Windows Update client to check for and install Windows Updates according to the computers Windows Update Settings
If a computer is set to use WSUS, an online check can be forced using the -ForceOnlineUpdate switch
.PARAMETER RestartOption
Specify if you want to restart the Virtual Machine upon Windows Update installation completion
"Example: AutoReboot or IgnoreReboot"
.PARAMETER ForceOnlineUpdate
This is a switch that will force the computer to check online for Windows Updates
.EXAMPLE
.\Invoke-WindowsUpdate.ps1 -RestartOption 'AutoReboot'
#>
[CmdletBinding()]
param
(
[parameter(Mandatory=$true,HelpMessage="Example: AutoReboot or IgnoreReboot")]
[ValidateSet('AutoReboot', 'IgnoreReboot')]
$RestartOption,
[Switch]$ForceOnlineUpdate
)
# Get Script Start Time and Date
$DateTime = (Get-Date)
# Set Verbose and ErrorAction Preference
$VerbosePreference = 'Continue'
$ErrorActionPreference = 'Stop'
# Create Script Log File
$ScriptLogFilePath = New-Item -Path "$env:TEMP\InvokeWindowsUpdate.log" -ItemType File -Force
Add-Content -Path $ScriptLogFilePath -Value "Script Processing Started at $DateTime"
Function Invoke-WindowsUpdate
{
[CmdletBinding()]
Param
(
#Mode options
[Switch]$AcceptAll,
[Switch]$AutoReboot,
[Switch]$IgnoreReboot,
[Switch]$ForceOnlineUpdate
)
# Check for administrative rights, break if not Administrator
$User = [Security.Principal.WindowsIdentity]::GetCurrent()
$Role = (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if(!$Role)
{
Write-Warning "To perform some operations you must run an elevated Windows PowerShell console."
Break
}
# Get updates list
Write-Verbose "Getting updates list"
Add-Content -Path $ScriptLogFilePath -Value "Getting updates list"
$objServiceManager = New-Object -ComObject "Microsoft.Update.ServiceManager"
Write-Verbose "Create Microsoft.Update.Session object"
Add-Content -Path $ScriptLogFilePath -Value "Create Microsoft.Update.Session object"
$SessionObject = New-Object -ComObject "Microsoft.Update.Session"
Write-Verbose "Create Microsoft.Update.Session.Searcher object"
Add-Content -Path $ScriptLogFilePath -Value "Create Microsoft.Update.Session.Searcher object"
$objSearcher = $SessionObject.CreateUpdateSearcher()
# Check the registry for Windows Update settings and set searcher service
$WindowsUpdatePath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate"
$WindowsUpdateAUPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU"
if (!($ForceOnlineUpdate))
{
$WSUSRegistryValue = (Get-ItemProperty -Path $WindowsUpdatePath -Name WUServer -ErrorAction SilentlyContinue).WUServer
if ($WSUSRegistryValue)
{
Write-Verbose "Computer is set to use WSUS Server $WSUSRegistryValue"
Add-Content -Path $ScriptLogFilePath -Value "Computer is set to use WSUS Server $WSUSRegistryValue"
$objSearcher.ServerSelection = 1
}
if ([String]::IsNullOrEmpty($WSUSRegistryValue))
{
$FeaturedSoftwareRegistryValue = (Get-ItemProperty -Path $WindowsUpdateAUPath -Name EnableFeaturedSoftware -ErrorAction SilentlyContinue).EnableFeaturedSoftware
if ($FeaturedSoftwareRegistryValue)
{
Write-Verbose "Set source of updates to Microsoft Update"
Add-Content -Path $ScriptLogFilePath -Value "Set source of updates to Microsoft Update"
$serviceName = $null
foreach ($objService in $objServiceManager.Services)
{
If($objService.Name -eq "Microsoft Update")
{
$objSearcher.ServerSelection = 3
$objSearcher.ServiceID = $objService.ServiceID
$serviceName = $objService.Name
Break
}
}
}
else
{
Write-Verbose "Set source of updates to Windows Update"
Add-Content -Path $ScriptLogFilePath -Value "Set source of updates to Windows Update"
$objSearcher.ServerSelection = 2
$serviceName = "Windows Update"
}
}
}
if ($ForceOnlineUpdate)
{
$FeaturedSoftwareRegistryValue = (Get-ItemProperty -Path $WindowsUpdateAUPath -Name EnableFeaturedSoftware -ErrorAction SilentlyContinue).EnableFeaturedSoftware
if ($FeaturedSoftwareRegistryValue)
{
Write-Verbose "Set source of updates to Microsoft Update"
Add-Content -Path $ScriptLogFilePath -Value "Set source of updates to Microsoft Update"
$serviceName = $null
foreach ($objService in $objServiceManager.Services)
{
If($objService.Name -eq "Microsoft Update")
{
$objSearcher.ServerSelection = 3
$objSearcher.ServiceID = $objService.ServiceID
$serviceName = $objService.Name
Break
}
}
}
else
{
Write-Verbose "Set source of updates to Windows Update"
Add-Content -Path $ScriptLogFilePath -Value "Set source of updates to Windows Update"
$objSearcher.ServerSelection = 2
$serviceName = "Windows Update"
}
}
Write-Verbose "Connecting to $serviceName server. Please wait..."
Add-Content -Path $ScriptLogFilePath -Value "Connecting to $serviceName server. Please wait..."
Try
{
# Search for updates
$Search = 'IsInstalled = 0'
$objResults = $objSearcher.Search($Search)
}
Catch
{
If($_ -match "HRESULT: 0x80072EE2")
{
Write-Warning "Cannot connect to Windows Update server"
Add-Content -Path $ScriptLogFilePath -Value "Cannot connect to Windows Update server"
}
Return
}
$objCollectionUpdate = New-Object -ComObject "Microsoft.Update.UpdateColl"
$NumberOfUpdate = 1
$UpdatesExtraDataCollection = @{}
$PreFoundUpdatesToDownload = $objResults.Updates.count
Write-Verbose "Found $($PreFoundUpdatesToDownload) Updates in pre search criteria"
Add-Content -Path $ScriptLogFilePath -Value "Found $($PreFoundUpdatesToDownload) Updates in pre search criteria"
# Set updates to install variable
$UpdatesToInstall = $objResults.Updates
Foreach($Update in $UpdatesToInstall)
{
$UpdateAccess = $true
Write-Verbose "Found Update: $($Update.Title)"
Add-Content -Path $ScriptLogFilePath -Value "Found Update: $($Update.Title)"
If($UpdateAccess -eq $true)
{
# Convert update size so it is readable
Switch($Update.MaxDownloadSize)
{
{[System.Math]::Round($_/1KB,0) -lt 1024} { $Size = [String]([System.Math]::Round($_/1KB,0))+" KB"; break }
{[System.Math]::Round($_/1MB,0) -lt 1024} { $Size = [String]([System.Math]::Round($_/1MB,0))+" MB"; break }
{[System.Math]::Round($_/1GB,0) -lt 1024} { $Size = [String]([System.Math]::Round($_/1GB,0))+" GB"; break }
{[System.Math]::Round($_/1TB,0) -lt 1024} { $Size = [String]([System.Math]::Round($_/1TB,0))+" TB"; break }
default { $Size = $_+"B" }
}
# Convert KB Article IDs so it is readable
If($Update.KBArticleIDs -ne "")
{
$KB = "KB"+$Update.KBArticleIDs
}
Else
{
$KB = ""
}