forked from Azure/AzureStack-Tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AzureStack.Identity.psm1
1369 lines (1136 loc) · 69.9 KB
/
AzureStack.Identity.psm1
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
# Copyright (c) Microsoft Corporation. All rights reserved.
# See LICENSE.txt in the project root for license information.
<#
.Synopsis
Get the Guid of the directory tenant
.DESCRIPTION
This function fetches the OpenID configuration metadata from the identity system and parses the Directory TenantID out of it.
Azure Stack AD FS is configured to be a single tenanted identity system with a TenantID.
.EXAMPLE
Get-AzsDirectoryTenantIdentifier -authority https://login.windows.net/microsoft.onmicrosoft.com
.EXAMPLE
Get-AzsDirectoryTenantIdentifier -authority https://adfs.local.azurestack.external/adfs
#>
function Get-AzsDirectoryTenantidentifier {
[CmdletBinding()]
Param
(
# The Authority of the identity system, e.g. "https://login.windows.net/microsoft.onmicrosoft.com"
[Parameter(Mandatory = $true,
Position = 0)]
$Authority
)
return $(Invoke-RestMethod $("{0}/.well-known/openid-configuration" -f $authority.TrimEnd('/'))).issuer.TrimEnd('/').Split('/')[-1]
}
<#
.Synopsis
This function is used to create a Service Principal on the AD Graph in an AD FS topology
.DESCRIPTION
The command creates a certificate in the cert store of the local user and uses that certificate to create a Service Principal in the Azure Stack Stamp Active Directory.
.EXAMPLE
$servicePrincipal = New-AzsAdGraphServicePrincipal -DisplayName "myapp12" -AdminCredential $(Get-Credential) -Verbose
#>
function New-AzsAdGraphServicePrincipal {
[CmdletBinding()]
Param
(
# Display Name of the Service Principal
[ValidatePattern("[a-zA-Z0-9-]{3,}")]
[Parameter(Mandatory = $true,
Position = 0)]
$DisplayName,
# PEP Machine name
[string]
$ERCSMachineName = "Azs-ERCS01",
# Domain Administrator Credential to create Service Principal
[Parameter(Mandatory = $true,
Position = 2)]
[System.Management.Automation.PSCredential]
$AdminCredential
)
$ApplicationGroupName = $DisplayName
$computerName = $ERCSMachineName
$cloudAdminCredential = $AdminCredential
$domainAdminSession = New-PSSession -ComputerName $computerName -Credential $cloudAdminCredential -configurationname privilegedendpoint -Verbose
$GraphClientCertificate = New-SelfSignedCertificate -CertStoreLocation "cert:\CurrentUser\My" -Subject "CN=$ApplicationGroupName" -KeySpec KeyExchange
$graphRedirectUri = "https://localhost/".ToLowerInvariant()
$ApplicationName = $ApplicationGroupName
$application = Invoke-Command -Session $domainAdminSession -Verbose -ErrorAction Stop `
-ScriptBlock { New-GraphApplication -Name $using:ApplicationName -ClientRedirectUris $using:graphRedirectUri -ClientCertificates $using:GraphClientCertificate }
return $application
}
# Exposed Functions
<#
.Synopsis
Adds a Guest Directory Tenant to Azure Stack.
.DESCRIPTION
Running this cmdlet will add the specified directory tenant to the Azure Stack whitelist.
.EXAMPLE
$adminARMEndpoint = "https://adminmanagement.local.azurestack.external"
$azureStackDirectoryTenant = "<homeDirectoryTenant>.onmicrosoft.com"
$guestDirectoryTenantToBeOnboarded = "<guestDirectoryTenant>.onmicrosoft.com"
Register-AzsGuestDirectoryTenant -AdminResourceManagerEndpoint $adminARMEndpoint -DirectoryTenantName $azureStackDirectoryTenant -GuestDirectoryTenantName $guestDirectoryTenantToBeOnboarded
#>
function Register-AzsGuestDirectoryTenant {
[CmdletBinding()]
param
(
# The endpoint of the Azure Stack Resource Manager service.
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[ValidateScript( { $_.Scheme -eq [System.Uri]::UriSchemeHttps })]
[uri] $AdminResourceManagerEndpoint,
# The name of the home Directory Tenant in which the Azure Stack Administrator subscription resides.
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string] $DirectoryTenantName,
# The names of the guest Directory Tenants which are to be onboarded.
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string[]] $GuestDirectoryTenantName,
# The location of your Azure Stack deployment.
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string] $Location,
# The identifier of the Administrator Subscription. If not specified, the script will attempt to use the set default subscription.
[ValidateNotNull()]
[string] $SubscriptionId = $null,
# The display name of the Administrator Subscription. If not specified, the script will attempt to use the set default subscription.
[ValidateNotNull()]
[string] $SubscriptionName = $null,
# The name of the resource group in which the directory tenant registration resource should be created (resource group must already exist).
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string] $ResourceGroupName = $null,
# Optional: A credential used to authenticate with Azure Stack. Must support a non-interactive authentication flow. If not provided, the script will prompt for user credentials.
[Parameter()]
[ValidateNotNull()]
[pscredential] $AutomationCredential = $null
)
$ErrorActionPreference = 'Stop'
$VerbosePreference = 'Continue'
Import-Module 'AzureRm.Profile' -Verbose:$false 4> $null
function Invoke-Main {
# Initialize the Azure PowerShell module to communicate with Azure Stack. Will prompt user for credentials.
$azureEnvironment = Initialize-AzureRmEnvironment 'AzureStackAdmin'
$azureAccount = Initialize-AzureRmUserAccount $azureEnvironment
foreach ($directoryTenantName in $GuestDirectoryTenantName) {
# Resolve the guest directory tenant ID from the name
$directoryTenantId = (New-Object uri(Invoke-RestMethod "$($azureEnvironment.ActiveDirectoryAuthority.TrimEnd('/'))/$directoryTenantName/.well-known/openid-configuration").token_endpoint).AbsolutePath.Split('/')[1]
# Add (or update) the new directory tenant to the Azure Stack deployment
$params = @{
ApiVersion = '2015-11-01'
ResourceType = "Microsoft.Subscriptions.Admin/directoryTenants"
ResourceGroupName = $ResourceGroupName
ResourceName = $directoryTenantName
Location = $Location
Properties = @{ tenantId = $directoryTenantId }
}
# Check if resource group exists, create it if it doesn't
$rg = Get-AzureRmResourceGroup -Name $ResourceGroupName -Location $Location -ErrorAction SilentlyContinue
if ($rg -eq $null) {
New-AzureRmResourceGroup -Name $ResourceGroupName -Location $Location -ErrorAction SilentlyContinue | Out-Null
}
$directoryTenant = New-AzureRmResource @params -Force -Verbose -ErrorAction Stop
Write-Verbose -Message "Directory Tenant onboarded: $(ConvertTo-Json $directoryTenant)" -Verbose
}
}
function Initialize-AzureRmEnvironment([string]$environmentName) {
$endpoints = Invoke-RestMethod -Method Get -Uri "$($AdminResourceManagerEndpoint.ToString().TrimEnd('/'))/metadata/endpoints?api-version=2015-01-01" -Verbose
Write-Verbose -Message "Endpoints: $(ConvertTo-Json $endpoints)" -Verbose
# resolve the directory tenant ID from the name
$directoryTenantId = (New-Object uri(Invoke-RestMethod "$($endpoints.authentication.loginEndpoint.TrimEnd('/'))/$DirectoryTenantName/.well-known/openid-configuration").token_endpoint).AbsolutePath.Split('/')[1]
$azureEnvironmentParams = @{
Name = $environmentName
ActiveDirectoryEndpoint = $endpoints.authentication.loginEndpoint.TrimEnd('/') + "/"
ActiveDirectoryServiceEndpointResourceId = $endpoints.authentication.audiences[0]
AdTenant = $directoryTenantId
ResourceManagerEndpoint = $AdminResourceManagerEndpoint
GalleryEndpoint = $endpoints.galleryEndpoint
GraphEndpoint = $endpoints.graphEndpoint
GraphAudience = $endpoints.graphEndpoint
}
$azureEnvironment = Add-AzureRmEnvironment @azureEnvironmentParams -ErrorAction Ignore
$azureEnvironment = Get-AzureRmEnvironment -Name $environmentName -ErrorAction Stop
return $azureEnvironment
}
function Initialize-AzureRmUserAccount([Microsoft.Azure.Commands.Profile.Models.PSAzureEnvironment]$azureEnvironment) {
$params = @{
EnvironmentName = $azureEnvironment.Name
TenantId = $azureEnvironment.AdTenant
}
if ($AutomationCredential) {
$params += @{ Credential = $AutomationCredential }
}
# Prompts the user for interactive login flow if automation credential is not specified
#$DebugPreference = "Continue"
$azureAccount = Add-AzureRmAccount @params
if ($SubscriptionName) {
Select-AzureRmSubscription -SubscriptionName $SubscriptionName | Out-Null
}
elseif ($SubscriptionId) {
Select-AzureRmSubscription -SubscriptionId $SubscriptionId | Out-Null
}
return $azureAccount
}
Invoke-Main
}
<#
.Synopsis
Gets the health report of identity application in the Azure Stack home and guest directories
.DESCRIPTION
Gets the health report for Azure Stack identity applications in the home directory as well as guest directories of Azure Stack. Any directories with an unhealthy status need to have their permissions updated.
.EXAMPLE
$adminResourceManagerEndpoint = "https://adminmanagement.local.azurestack.external"
$homeDirectoryTenantName = "<homeDirectoryTenant>.onmicrosoft.com"
Get-AzsHealthReport -AdminResourceManagerEndpoint $adminResourceManagerEndpoint `
-DirectoryTenantName $homeDirectoryTenantName -Verbose
#>
function Get-AzsHealthReport {
[CmdletBinding()]
param
(
# The endpoint of the Azure Stack Resource Manager service.
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[ValidateScript( { $_.Scheme -eq [System.Uri]::UriSchemeHttps })]
[uri] $AdminResourceManagerEndpoint,
# The name of the home Directory Tenant in which the Azure Stack Administrator subscription resides.
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string] $DirectoryTenantName,
# Optional: A credential used to authenticate with Azure Stack. Must support a non-interactive authentication flow. If not provided, the script will prompt for user credentials.
[Parameter()]
[ValidateNotNull()]
[pscredential] $AutomationCredential = $null
)
$ErrorActionPreference = 'Stop'
$VerbosePreference = 'Continue'
# Install-Module AzureRm
Import-Module 'AzureRm.Profile' -Verbose:$false 4> $null
Import-Module "$PSScriptRoot\GraphAPI\GraphAPI.psm1" -Verbose:$false 4> $null
function Invoke-Main {
# Initialize the Azure PowerShell module to communicate with the Azure Resource Manager in the public cloud corresponding to the Azure Stack Graph Service. Will prompt user for credentials.
Write-Host "Authenticating user..."
$azureStackEnvironment = Initialize-AzureRmEnvironment 'AzureStackAdmin'
$refreshToken = Initialize-AzureRmUserAccount $azureStackEnvironment
# Initialize the Graph PowerShell module to communicate with the correct graph service
$graphEnvironment = Resolve-GraphEnvironment $azureStackEnvironment
Initialize-GraphEnvironment -Environment $graphEnvironment -DirectoryTenantId $DirectoryTenantName -RefreshToken $refreshToken
# Call Azure Stack Resource Manager to retrieve the list of registered applications which need to be initialized in the onboarding directory tenant
Write-Host "Acquiring an access token to communicate with Resource Manager..."
$armAccessToken = Get-ArmAccessToken $azureStackEnvironment
$defaultProviderSubscription = Get-AzureRmSubscription -SubscriptionName "Default Provider Subscription"
$healthReportUrl = "$($AdminResourceManagerEndpoint.AbsoluteUri)/subscriptions/$($defaultProviderSubscription.SubscriptionId)/providers/Microsoft.Subscriptions.Admin/checkIdentityHealth?api-version=2018-05-01"
$headers = @{ "Authorization" = "Bearer $armAccessToken" }
$healthReport = (Invoke-WebRequest -Headers $headers -Uri $healthReportUrl -Method Post -UseBasicParsing -TimeoutSec 40).Content | ConvertFrom-Json
return $healthReport
}
function Initialize-AzureRmEnvironment([string]$environmentName) {
$endpoints = Invoke-RestMethod -Method Get -Uri "$($AdminResourceManagerEndpoint.ToString().TrimEnd('/'))/metadata/endpoints?api-version=2015-01-01" -Verbose
Write-Verbose -Message "Endpoints: $(ConvertTo-Json $endpoints)" -Verbose
# resolve the directory tenant ID from the name
$directoryTenantId = (New-Object uri(Invoke-RestMethod "$($endpoints.authentication.loginEndpoint.TrimEnd('/'))/$DirectoryTenantName/.well-known/openid-configuration").token_endpoint).AbsolutePath.Split('/')[1]
$azureEnvironmentParams = @{
Name = $environmentName
ActiveDirectoryEndpoint = $endpoints.authentication.loginEndpoint.TrimEnd('/') + "/"
ActiveDirectoryServiceEndpointResourceId = $endpoints.authentication.audiences[0]
AdTenant = $directoryTenantId
ResourceManagerEndpoint = $AdminResourceManagerEndpoint
GalleryEndpoint = $endpoints.galleryEndpoint
GraphEndpoint = $endpoints.graphEndpoint
GraphAudience = $endpoints.graphEndpoint
}
$azureEnvironment = Add-AzureRmEnvironment @azureEnvironmentParams -ErrorAction Ignore
$azureEnvironment = Get-AzureRmEnvironment -Name $environmentName -ErrorAction Stop
return $azureEnvironment
}
function Initialize-AzureRmUserAccount([Microsoft.Azure.Commands.Profile.Models.PSAzureEnvironment]$azureStackEnvironment) {
$params = @{
EnvironmentName = $azureStackEnvironment.Name
TenantId = $azureStackEnvironment.AdTenant
}
if ($AutomationCredential) {
$params += @{ Credential = $AutomationCredential }
}
# Prompts the user for interactive login flow if automation credential is not specified
$azureStackAccount = Add-AzureRmAccount @params
# Retrieve the refresh token
$tokens = @()
$tokens += try { [Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache]::DefaultShared.ReadItems() } catch { }
$tokens += try { [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.TokenCache.ReadItems() } catch { }
$refreshToken = $tokens |
Where Resource -EQ $azureStackEnvironment.ActiveDirectoryServiceEndpointResourceId |
Where IsMultipleResourceRefreshToken -EQ $true |
Where DisplayableId -EQ $azureStackAccount.Context.Account.Id |
Sort ExpiresOn |
Select -Last 1 -ExpandProperty RefreshToken |
ConvertTo-SecureString -AsPlainText -Force
# Workaround due to regression in AzurePowerShell profile module which fails to populate the response object of "Add-AzureRmAccount" cmdlet
if (-not $refreshToken) {
if ($tokens.Count -eq 1) {
Write-Warning "Failed to find target refresh token from Azure PowerShell Cache; attempting to reuse the single cached auth context..."
$refreshToken = $tokens[0].RefreshToken | ConvertTo-SecureString -AsPlainText -Force
}
else {
throw "Unable to find refresh token from Azure PowerShell Cache. Please try the command again in a fresh PowerShell instance after running 'Clear-AzureRmContext -Scope CurrentUser -Force -Verbose'."
}
}
return $refreshToken
}
function Resolve-GraphEnvironment([Microsoft.Azure.Commands.Profile.Models.PSAzureEnvironment]$azureEnvironment) {
$graphEnvironment = switch ($azureEnvironment.ActiveDirectoryAuthority) {
'https://login.microsoftonline.com/' { 'AzureCloud' }
'https://login.chinacloudapi.cn/' { 'AzureChinaCloud' }
'https://login-us.microsoftonline.com/' { 'AzureUSGovernment' }
'https://login.microsoftonline.us/' { 'AzureUSGovernment' }
'https://login.microsoftonline.de/' { 'AzureGermanCloud' }
Default { throw "Unsupported graph resource identifier: $_" }
}
return $graphEnvironment
}
function Get-ArmAccessToken([Microsoft.Azure.Commands.Profile.Models.PSAzureEnvironment]$azureStackEnvironment) {
$armAccessToken = $null
$attempts = 0
$maxAttempts = 12
$delayInSeconds = 5
do {
try {
$attempts++
$armAccessToken = (Get-GraphToken -Resource $azureStackEnvironment.ActiveDirectoryServiceEndpointResourceId -UseEnvironmentData -ErrorAction Stop).access_token
}
catch {
if ($attempts -ge $maxAttempts) {
throw
}
Write-Verbose "Error attempting to acquire ARM access token: $_`r`n$($_.Exception)" -Verbose
Write-Verbose "Delaying for $delayInSeconds seconds before trying again... (attempt $attempts/$maxAttempts)" -Verbose
Start-Sleep -Seconds $delayInSeconds
}
}
while (-not $armAccessToken)
return $armAccessToken
}
$logFile = Join-Path -Path $PSScriptRoot -ChildPath "$DirectoryTenantName.$(Get-Date -Format MM-dd_HH-mm-ss_ms).log"
Write-Verbose "Logging additional information to log file '$logFile'" -Verbose
$logStartMessage = "[$(Get-Date -Format 'hh:mm:ss tt')] - Beginning invocation of '$($MyInvocation.InvocationName)' with parameters: $(ConvertTo-Json $PSBoundParameters -Depth 4)"
$logStartMessage >> $logFile
try {
# Redirect verbose output to a log file
Invoke-Main 4>> $logFile
$logEndMessage = "[$(Get-Date -Format 'hh:mm:ss tt')] - Script completed successfully."
$logEndMessage >> $logFile
}
catch {
$logErrorMessage = "[$(Get-Date -Format 'hh:mm:ss tt')] - Script terminated with error: $_`r`n$($_.Exception)"
$logErrorMessage >> $logFile
Write-Warning "An error has occurred; more information may be found in the log file '$logFile'" -WarningAction Continue
throw
}
}
<#
.Synopsis
Consents to any missing permissions for Azure Stack identity applications in the home directory of Azure Stack.
.DESCRIPTION
Consents to any missing permissions for Azure Stack identity applications in the home directory of Azure Stack. This is needed to complete the "installation" of new Resource Provider identity applications in Azure Stack.
.EXAMPLE
$adminResourceManagerEndpoint = "https://adminmanagement.local.azurestack.external"
$homeDirectoryTenantName = "<homeDirectoryTenant>.onmicrosoft.com"
Update-AzsHomeDirectoryTenant -AdminResourceManagerEndpoint $adminResourceManagerEndpoint `
-DirectoryTenantName $homeDirectoryTenantName -Verbose
#>
function Update-AzsHomeDirectoryTenant {
[CmdletBinding()]
param
(
# The endpoint of the Azure Stack Resource Manager service.
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[ValidateScript( { $_.Scheme -eq [System.Uri]::UriSchemeHttps })]
[uri] $AdminResourceManagerEndpoint,
# The name of the home Directory Tenant in which the Azure Stack Administrator subscription resides.
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string] $DirectoryTenantName,
# Optional: A credential used to authenticate with Azure Stack. Must support a non-interactive authentication flow. If not provided, the script will prompt for user credentials.
[Parameter()]
[ValidateNotNull()]
[pscredential] $AutomationCredential = $null
)
$ErrorActionPreference = 'Stop'
$VerbosePreference = 'Continue'
Import-Module 'AzureRm.Profile' -Verbose:$false 4> $null
Import-Module "$PSScriptRoot\GraphAPI\GraphAPI.psm1" -Verbose:$false 4> $null
function Invoke-Main {
# Initialize the Azure PowerShell module to communicate with the Azure Resource Manager in the public cloud corresponding to the Azure Stack Graph Service. Will prompt user for credentials.
Write-Host "Authenticating user..."
$azureStackEnvironment = Initialize-AzureRmEnvironment 'AzureStackAdmin'
$refreshToken = Initialize-AzureRmUserAccount $azureStackEnvironment
# Initialize the Graph PowerShell module to communicate with the correct graph service
$graphEnvironment = Resolve-GraphEnvironment $azureStackEnvironment
Initialize-GraphEnvironment -Environment $graphEnvironment -DirectoryTenantId $DirectoryTenantName -RefreshToken $refreshToken
# Call Azure Stack Resource Manager to retrieve the list of registered applications which need to be initialized in the onboarding directory tenant
Write-Host "Acquiring an access token to communicate with Resource Manager..."
$armAccessToken = Get-ArmAccessToken $azureStackEnvironment
Write-Host "Looking-up the registered identity applications which need to be installed in your directory..."
$applicationRegistrationParams = @{
Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Get
Headers = @{ Authorization = "Bearer $armAccessToken" }
Uri = "$($AdminResourceManagerEndpoint.ToString().TrimEnd('/'))/applicationRegistrations?api-version=2014-04-01-preview"
}
$applicationRegistrations = Invoke-RestMethod @applicationRegistrationParams | Select -ExpandProperty value
# Identify which permissions have already been granted to each registered application and which additional permissions need to be granted
$permissions = @()
$count = 0
foreach ($applicationRegistration in $applicationRegistrations) {
# Initialize the service principal for the registered application
$count++
$applicationServicePrincipal = Initialize-GraphApplicationServicePrincipal -ApplicationId $applicationRegistration.appId
Write-Host "Installing Application... ($($count) of $($applicationRegistrations.Count)): $($applicationServicePrincipal.appId) '$($applicationServicePrincipal.appDisplayName)'"
# WORKAROUND - the recent Azure Stack update has a missing permission registration; temporarily "inject" this permission registration into the returned data
if ($applicationServicePrincipal.servicePrincipalNames | Where { $_ -like 'https://deploymentprovider.*/*' }) {
Write-Verbose "Adding missing permission registrations for application '$($applicationServicePrincipal.appDisplayName)' ($($applicationServicePrincipal.appId))..." -Verbose
$graph = Get-GraphApplicationServicePrincipal -ApplicationId (Get-GraphEnvironmentInfo).Applications.WindowsAzureActiveDirectory.Id
$applicationRegistration.appRoleAssignments = @(
[pscustomobject]@{
resource = (Get-GraphEnvironmentInfo).Applications.WindowsAzureActiveDirectory.Id
client = $applicationRegistration.appId
roleId = $graph.appRoles | Where value -EQ 'Directory.Read.All' | Select -ExpandProperty id
},
[pscustomobject]@{
resource = (Get-GraphEnvironmentInfo).Applications.WindowsAzureActiveDirectory.Id
client = $applicationRegistration.appId
roleId = $graph.appRoles | Where value -EQ 'Application.ReadWrite.OwnedBy' | Select -ExpandProperty id
}
)
}
# Initialize the necessary tags for the registered application
if ($applicationRegistration.tags) {
Update-GraphApplicationServicePrincipalTags -ApplicationId $applicationRegistration.appId -Tags $applicationRegistration.tags
}
# Lookup the permission consent status for the *application* permissions (either to or from) which the registered application requires
foreach ($appRoleAssignment in $applicationRegistration.appRoleAssignments) {
$params = @{
ClientApplicationId = $appRoleAssignment.client
ResourceApplicationId = $appRoleAssignment.resource
PermissionType = 'Application'
PermissionId = $appRoleAssignment.roleId
}
$permissions += New-GraphPermissionDescription @params -LookupConsentStatus
}
# Lookup the permission consent status for the *delegated* permissions (either to or from) which the registered application requires
foreach ($oauth2PermissionGrant in $applicationRegistration.oauth2PermissionGrants) {
$resourceApplicationServicePrincipal = Initialize-GraphApplicationServicePrincipal -ApplicationId $oauth2PermissionGrant.resource
foreach ($scope in $oauth2PermissionGrant.scope.Split(' ')) {
$params = @{
ClientApplicationId = $oauth2PermissionGrant.client
ResourceApplicationServicePrincipal = $resourceApplicationServicePrincipal
PermissionType = 'Delegated'
PermissionId = ($resourceApplicationServicePrincipal.oauth2Permissions | Where value -EQ $scope).id
}
$permissions += New-GraphPermissionDescription @params -LookupConsentStatus
}
}
}
# Trace the permission status
Write-Verbose "Current permission status: $($permissions | ConvertTo-Json -Depth 4)" -Verbose
$permissionFile = Join-Path -Path $PSScriptRoot -ChildPath "$DirectoryTenantName.permissions.json"
$permissionContent = $permissions | Select -Property * -ExcludeProperty isConsented | ConvertTo-Json -Depth 4 | Out-String
$permissionContent > $permissionFile
# Display application status to user
$permissionsByClient = $permissions | Select *, @{n = 'Client'; e = { '{0} {1}' -f $_.clientApplicationId, $_.clientApplicationDisplayName } } | Sort clientApplicationDisplayName | Group Client
$readyApplications = @()
$pendingApplications = @()
foreach ($client in $permissionsByClient) {
if ($client.Group.isConsented -Contains $false) {
$pendingApplications += $client
}
else {
$readyApplications += $client
}
}
Write-Host ""
if ($readyApplications) {
Write-Host "Applications installed and configured:"
Write-Host "`t$($readyApplications.Name -join "`r`n`t")"
}
if ($readyApplications -and $pendingApplications) {
Write-Host ""
}
if ($pendingApplications) {
Write-Host "Applications waiting to be configured:"
Write-Host "`t$($pendingApplications.Name -join "`r`n`t")"
}
Write-Host ""
# Grant any missing permissions for registered applications
if ($permissions | Where isConsented -EQ $false | Select -First 1) {
Write-Host "Configuring applications... (this may take up to a few minutes to complete)"
Write-Host ""
$permissions | Where isConsented -EQ $false | Grant-GraphApplicationPermission
}
Write-Host "All applications installed and configured! Your home directory '$DirectoryTenantName' has been successfully updated to be used with Azure Stack!"
Write-Host ""
Write-Host "A more detailed description of the applications installed and with what permissions they have been configured can be found in the file '$permissionFile'."
Write-Host "Run this script again at any time to check the status of the Azure Stack applications in your directory."
Write-Warning "If your Azure Stack Administrator installs new services or updates in the future, you may need to run this script again."
}
function Initialize-AzureRmEnvironment([string]$environmentName) {
$endpoints = Invoke-RestMethod -Method Get -Uri "$($AdminResourceManagerEndpoint.ToString().TrimEnd('/'))/metadata/endpoints?api-version=2015-01-01" -Verbose
Write-Verbose -Message "Endpoints: $(ConvertTo-Json $endpoints)" -Verbose
# resolve the directory tenant ID from the name
$directoryTenantId = (New-Object uri(Invoke-RestMethod "$($endpoints.authentication.loginEndpoint.TrimEnd('/'))/$DirectoryTenantName/.well-known/openid-configuration").token_endpoint).AbsolutePath.Split('/')[1]
$azureEnvironmentParams = @{
Name = $environmentName
ActiveDirectoryEndpoint = $endpoints.authentication.loginEndpoint.TrimEnd('/') + "/"
ActiveDirectoryServiceEndpointResourceId = $endpoints.authentication.audiences[0]
AdTenant = $directoryTenantId
ResourceManagerEndpoint = $AdminResourceManagerEndpoint
GalleryEndpoint = $endpoints.galleryEndpoint
GraphEndpoint = $endpoints.graphEndpoint
GraphAudience = $endpoints.graphEndpoint
}
$azureEnvironment = Add-AzureRmEnvironment @azureEnvironmentParams -ErrorAction Ignore
$azureEnvironment = Get-AzureRmEnvironment -Name $environmentName -ErrorAction Stop
return $azureEnvironment
}
function Initialize-AzureRmUserAccount([Microsoft.Azure.Commands.Profile.Models.PSAzureEnvironment]$azureStackEnvironment) {
$params = @{
EnvironmentName = $azureStackEnvironment.Name
TenantId = $azureStackEnvironment.AdTenant
}
if ($AutomationCredential) {
$params += @{ Credential = $AutomationCredential }
}
# Prompts the user for interactive login flow if automation credential is not specified
$azureStackAccount = Add-AzureRmAccount @params
# Retrieve the refresh token
$tokens = @()
$tokens += try { [Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache]::DefaultShared.ReadItems() } catch { }
$tokens += try { [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.TokenCache.ReadItems() } catch { }
$refreshToken = $tokens |
Where Resource -EQ $azureStackEnvironment.ActiveDirectoryServiceEndpointResourceId |
Where IsMultipleResourceRefreshToken -EQ $true |
Where DisplayableId -EQ $azureStackAccount.Context.Account.Id |
Sort ExpiresOn |
Select -Last 1 -ExpandProperty RefreshToken |
ConvertTo-SecureString -AsPlainText -Force
# Workaround due to regression in AzurePowerShell profile module which fails to populate the response object of "Add-AzureRmAccount" cmdlet
if (-not $refreshToken) {
if ($tokens.Count -eq 1) {
Write-Warning "Failed to find target refresh token from Azure PowerShell Cache; attempting to reuse the single cached auth context..."
$refreshToken = $tokens[0].RefreshToken | ConvertTo-SecureString -AsPlainText -Force
}
else {
throw "Unable to find refresh token from Azure PowerShell Cache. Please try the command again in a fresh PowerShell instance after running 'Clear-AzureRmContext -Scope CurrentUser -Force -Verbose'."
}
}
return $refreshToken
}
function Resolve-GraphEnvironment([Microsoft.Azure.Commands.Profile.Models.PSAzureEnvironment]$azureEnvironment) {
$graphEnvironment = switch ($azureEnvironment.ActiveDirectoryAuthority) {
'https://login.microsoftonline.com/' { 'AzureCloud' }
'https://login.chinacloudapi.cn/' { 'AzureChinaCloud' }
'https://login-us.microsoftonline.com/' { 'AzureUSGovernment' }
'https://login.microsoftonline.us/' { 'AzureUSGovernment' }
'https://login.microsoftonline.de/' { 'AzureGermanCloud' }
Default { throw "Unsupported graph resource identifier: $_" }
}
return $graphEnvironment
}
function Get-ArmAccessToken([Microsoft.Azure.Commands.Profile.Models.PSAzureEnvironment]$azureStackEnvironment) {
$armAccessToken = $null
$attempts = 0
$maxAttempts = 12
$delayInSeconds = 5
do {
try {
$attempts++
$armAccessToken = (Get-GraphToken -Resource $azureStackEnvironment.ActiveDirectoryServiceEndpointResourceId -UseEnvironmentData -ErrorAction Stop).access_token
}
catch {
if ($attempts -ge $maxAttempts) {
throw
}
Write-Verbose "Error attempting to acquire ARM access token: $_`r`n$($_.Exception)" -Verbose
Write-Verbose "Delaying for $delayInSeconds seconds before trying again... (attempt $attempts/$maxAttempts)" -Verbose
Start-Sleep -Seconds $delayInSeconds
}
}
while (-not $armAccessToken)
return $armAccessToken
}
$logFile = Join-Path -Path $PSScriptRoot -ChildPath "$DirectoryTenantName.$(Get-Date -Format MM-dd_HH-mm-ss_ms).log"
Write-Verbose "Logging additional information to log file '$logFile'" -Verbose
$logStartMessage = "[$(Get-Date -Format 'hh:mm:ss tt')] - Beginning invocation of '$($MyInvocation.InvocationName)' with parameters: $(ConvertTo-Json $PSBoundParameters -Depth 4)"
$logStartMessage >> $logFile
try {
# Redirect verbose output to a log file
Invoke-Main 4>> $logFile
$logEndMessage = "[$(Get-Date -Format 'hh:mm:ss tt')] - Script completed successfully."
$logEndMessage >> $logFile
}
catch {
$logErrorMessage = "[$(Get-Date -Format 'hh:mm:ss tt')] - Script terminated with error: $_`r`n$($_.Exception)"
$logErrorMessage >> $logFile
Write-Warning "An error has occurred; more information may be found in the log file '$logFile'" -WarningAction Continue
throw
}
}
<#
.Synopsis
Consents to the given Azure Stack instance within the callers's Azure Directory Tenant.
.DESCRIPTION
Consents to the given Azure Stack instance within the callers's Azure Directory Tenant. This is needed to propagate Azure Stack applications into the user's directory tenant.
.EXAMPLE
$tenantARMEndpoint = "https://management.local.azurestack.external"
$myDirectoryTenantName = "<guestDirectoryTenant>.onmicrosoft.com"
Register-AzsWithMyDirectoryTenant -TenantResourceManagerEndpoint $tenantARMEndpoint `
-DirectoryTenantName $myDirectoryTenantName -Verbose -Debug
#>
function Register-AzsWithMyDirectoryTenant {
[CmdletBinding()]
param
(
# The endpoint of the Azure Stack Resource Manager service.
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[ValidateScript( { $_.Scheme -eq [System.Uri]::UriSchemeHttps })]
[uri] $TenantResourceManagerEndpoint,
# The name of the directory tenant being onboarded.
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string] $DirectoryTenantName,
# Optional: A credential used to authenticate with Azure Stack. Must support a non-interactive authentication flow. If not provided, the script will prompt for user credentials.
[Parameter()]
[ValidateNotNull()]
[pscredential] $AutomationCredential = $null
)
$ErrorActionPreference = 'Stop'
$VerbosePreference = 'Continue'
Import-Module 'AzureRm.Profile' -Verbose:$false 4> $null
Import-Module "$PSScriptRoot\GraphAPI\GraphAPI.psm1" -Verbose:$false 4> $null
function Invoke-Main {
# Initialize the Azure PowerShell module to communicate with the Azure Resource Manager in the public cloud corresponding to the Azure Stack Graph Service. Will prompt user for credentials.
Write-Host "Authenticating user..."
$azureStackEnvironment = Initialize-AzureRmEnvironment 'AzureStack'
$azureEnvironment = Resolve-AzureEnvironment $azureStackEnvironment
$refreshToken = Initialize-AzureRmUserAccount $azureEnvironment $azureStackEnvironment.AdTenant
# Initialize the Graph PowerShell module to communicate with the correct graph service
$graphEnvironment = Resolve-GraphEnvironment $azureEnvironment
Initialize-GraphEnvironment -Environment $graphEnvironment -DirectoryTenantId $DirectoryTenantName -RefreshToken $refreshToken
# Initialize the service principal for the Azure Stack Resource Manager application
Write-Host "Installing Resource Manager in your directory ('$DirectoryTenantName')..."
$resourceManagerServicePrincipal = Initialize-ResourceManagerServicePrincipal
# Authorize the Azure Powershell module to act as a client to call the Azure Stack Resource Manager in the onboarding directory tenant
Write-Host "Authorizing the Azure PowerShell module to communicate with Resource Manager in your directory..."
Initialize-GraphOAuth2PermissionGrant -ClientApplicationId (Get-GraphEnvironmentInfo).Applications.PowerShell.Id -ResourceApplicationIdentifierUri $azureStackEnvironment.ActiveDirectoryServiceEndpointResourceId
# Call Azure Stack Resource Manager to retrieve the list of registered applications which need to be initialized in the onboarding directory tenant
Write-Host "Acquiring an access token to communicate with Resource Manager... (this may take up to a few minutes to complete)"
$armAccessToken = Get-ArmAccessToken $azureStackEnvironment
Write-Host "Looking-up the registered identity applications which need to be installed in your directory..."
$applicationRegistrationParams = @{
Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Get
Headers = @{ Authorization = "Bearer $armAccessToken" }
Uri = "$($TenantResourceManagerEndpoint.ToString().TrimEnd('/'))/applicationRegistrations?api-version=2014-04-01-preview"
}
$applicationRegistrations = Invoke-RestMethod @applicationRegistrationParams | Select -ExpandProperty value
# Identify which permissions have already been granted to each registered application and which additional permissions need to be granted
$permissions = @()
$count = 0
foreach ($applicationRegistration in $applicationRegistrations) {
# Initialize the service principal for the registered application
$count++
$applicationServicePrincipal = Initialize-GraphApplicationServicePrincipal -ApplicationId $applicationRegistration.appId
Write-Host "Installing Application... ($($count) of $($applicationRegistrations.Count)): $($applicationServicePrincipal.appId) '$($applicationServicePrincipal.appDisplayName)'"
# Initialize the necessary tags for the registered application
if ($applicationRegistration.tags) {
Update-GraphApplicationServicePrincipalTags -ApplicationId $applicationRegistration.appId -Tags $applicationRegistration.tags
}
# Lookup the permission consent status for the *application* permissions (either to or from) which the registered application requires
foreach ($appRoleAssignment in $applicationRegistration.appRoleAssignments) {
$params = @{
ClientApplicationId = $appRoleAssignment.client
ResourceApplicationId = $appRoleAssignment.resource
PermissionType = 'Application'
PermissionId = $appRoleAssignment.roleId
}
$permissions += New-GraphPermissionDescription @params -LookupConsentStatus
}
# Lookup the permission consent status for the *delegated* permissions (either to or from) which the registered application requires
foreach ($oauth2PermissionGrant in $applicationRegistration.oauth2PermissionGrants) {
$resourceApplicationServicePrincipal = Initialize-GraphApplicationServicePrincipal -ApplicationId $oauth2PermissionGrant.resource
foreach ($scope in $oauth2PermissionGrant.scope.Split(' ')) {
$params = @{
ClientApplicationId = $oauth2PermissionGrant.client
ResourceApplicationServicePrincipal = $resourceApplicationServicePrincipal
PermissionType = 'Delegated'
PermissionId = ($resourceApplicationServicePrincipal.oauth2Permissions | Where value -EQ $scope).id
}
$permissions += New-GraphPermissionDescription @params -LookupConsentStatus
}
}
}
# Trace the permission status
Write-Verbose "Current permission status: $($permissions | ConvertTo-Json -Depth 4)" -Verbose
$permissionFile = Join-Path -Path $PSScriptRoot -ChildPath "$DirectoryTenantName.permissions.json"
$permissionContent = $permissions | Select -Property * -ExcludeProperty isConsented | ConvertTo-Json -Depth 4 | Out-String
$permissionContent > $permissionFile
# Display application status to user
$permissionsByClient = $permissions | Select *, @{n = 'Client'; e = { '{0} {1}' -f $_.clientApplicationId, $_.clientApplicationDisplayName } } | Sort clientApplicationDisplayName | Group Client
$readyApplications = @()
$pendingApplications = @()
foreach ($client in $permissionsByClient) {
if ($client.Group.isConsented -Contains $false) {
$pendingApplications += $client
}
else {
$readyApplications += $client
}
}
Write-Host ""
if ($readyApplications) {
Write-Host "Applications installed and configured:"
Write-Host "`t$($readyApplications.Name -join "`r`n`t")"
}
if ($readyApplications -and $pendingApplications) {
Write-Host ""
}
if ($pendingApplications) {
Write-Host "Applications waiting to be configured:"
Write-Host "`t$($pendingApplications.Name -join "`r`n`t")"
}
Write-Host ""
# Grant any missing permissions for registered applications
if ($permissions | Where isConsented -EQ $false | Select -First 1) {
Write-Host "Configuring applications... (this may take up to a few minutes to complete)"
Write-Host ""
$permissions | Where isConsented -EQ $false | Grant-GraphApplicationPermission
}
Write-Host "All applications installed and configured! Your directory '$DirectoryTenantName' has been successfully onboarded and can now be used with Azure Stack!"
Write-Host ""
Write-Host "A more detailed description of the applications installed and with what permissions they have been configured can be found in the file '$permissionFile'."
Write-Host "Run this script again at any time to check the status of the Azure Stack applications in your directory."
Write-Warning "If your Azure Stack Administrator installs new services or updates in the future, you may need to run this script again."
}
function Initialize-AzureRmEnvironment([string]$environmentName) {
$endpoints = Invoke-RestMethod -Method Get -Uri "$($TenantResourceManagerEndpoint.ToString().TrimEnd('/'))/metadata/endpoints?api-version=2015-01-01" -Verbose
Write-Verbose -Message "Endpoints: $(ConvertTo-Json $endpoints)" -Verbose
# resolve the directory tenant ID from the name
$directoryTenantId = (New-Object uri(Invoke-RestMethod "$($endpoints.authentication.loginEndpoint.TrimEnd('/'))/$DirectoryTenantName/.well-known/openid-configuration").token_endpoint).AbsolutePath.Split('/')[1]
$azureEnvironmentParams = @{
Name = $environmentName
ActiveDirectoryEndpoint = $endpoints.authentication.loginEndpoint.TrimEnd('/') + "/"
ActiveDirectoryServiceEndpointResourceId = $endpoints.authentication.audiences[0]
AdTenant = $directoryTenantId
ResourceManagerEndpoint = $TenantResourceManagerEndpoint
GalleryEndpoint = $endpoints.galleryEndpoint
GraphEndpoint = $endpoints.graphEndpoint
GraphAudience = $endpoints.graphEndpoint
}
$azureEnvironment = Add-AzureRmEnvironment @azureEnvironmentParams -ErrorAction Ignore
$azureEnvironment = Get-AzureRmEnvironment -Name $environmentName -ErrorAction Stop
return $azureEnvironment
}
function Resolve-AzureEnvironment([Microsoft.Azure.Commands.Profile.Models.PSAzureEnvironment]$azureStackEnvironment) {
$azureEnvironment = Get-AzureRmEnvironment |
Where GraphEndpointResourceId -EQ $azureStackEnvironment.GraphEndpointResourceId |
Where Name -In @('AzureCloud', 'AzureChinaCloud', 'AzureUSGovernment', 'AzureGermanCloud')
# Differentiate between AzureCloud and AzureUSGovernment
if ($azureEnvironment.Count -ge 2) {
$name = if ($azureStackEnvironment.ActiveDirectoryAuthority -eq 'https://login-us.microsoftonline.com/' -or $azureStackEnvironment.ActiveDirectoryAuthority -eq 'https://login.microsoftonline.us/') { 'AzureUSGovernment' } else { 'AzureCloud' }
$azureEnvironment = $azureEnvironment | Where Name -EQ $name
}
return $azureEnvironment
}
function Initialize-AzureRmUserAccount([Microsoft.Azure.Commands.Profile.Models.PSAzureEnvironment]$azureEnvironment, [string]$directoryTenantId) {
$params = @{
EnvironmentName = $azureEnvironment.Name
TenantId = $directoryTenantId
}
if ($AutomationCredential) {
$params += @{ Credential = $AutomationCredential }
}
# Prompts the user for interactive login flow if automation credential is not specified
$azureAccount = Add-AzureRmAccount @params
# Retrieve the refresh token
$tokens = @()
$tokens += try { [Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache]::DefaultShared.ReadItems() } catch { }
$tokens += try { [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.TokenCache.ReadItems() } catch { }
$refreshToken = $tokens |
Where Resource -EQ $azureEnvironment.ActiveDirectoryServiceEndpointResourceId |
Where IsMultipleResourceRefreshToken -EQ $true |
Where DisplayableId -EQ $azureAccount.Context.Account.Id |
Sort ExpiresOn |
Select -Last 1 -ExpandProperty RefreshToken |
ConvertTo-SecureString -AsPlainText -Force
# Workaround due to regression in AzurePowerShell profile module which fails to populate the response object of "Add-AzureRmAccount" cmdlet
if (-not $refreshToken) {
if ($tokens.Count -eq 1) {
Write-Warning "Failed to find target refresh token from Azure PowerShell Cache; attempting to reuse the single cached auth context..."
$refreshToken = $tokens[0].RefreshToken | ConvertTo-SecureString -AsPlainText -Force
}
else {
throw "Unable to find refresh token from Azure PowerShell Cache. Please try the command again in a fresh PowerShell instance after running 'Clear-AzureRmContext -Scope CurrentUser -Force -Verbose'."
}
}
return $refreshToken
}
function Resolve-GraphEnvironment([Microsoft.Azure.Commands.Profile.Models.PSAzureEnvironment]$azureEnvironment) {
$graphEnvironment = switch ($azureEnvironment.ActiveDirectoryAuthority) {
'https://login.microsoftonline.com/' { 'AzureCloud' }
'https://login.chinacloudapi.cn/' { 'AzureChinaCloud' }
'https://login-us.microsoftonline.com/' { 'AzureUSGovernment' }
'https://login.microsoftonline.us/' { 'AzureUSGovernment' }
'https://login.microsoftonline.de/' { 'AzureGermanCloud' }
Default { throw "Unsupported graph resource identifier: $_" }
}
return $graphEnvironment
}
function Initialize-ResourceManagerServicePrincipal {
$identityInfo = Invoke-RestMethod -Method Get -Uri "$($TenantResourceManagerEndpoint.ToString().TrimEnd('/'))/metadata/identity?api-version=2015-01-01" -Verbose
Write-Verbose -Message "Resource Manager identity information: $(ConvertTo-Json $identityInfo)" -Verbose
$resourceManagerServicePrincipal = Initialize-GraphApplicationServicePrincipal -ApplicationId $identityInfo.applicationId -Verbose
return $resourceManagerServicePrincipal
}
function Get-ArmAccessToken([Microsoft.Azure.Commands.Profile.Models.PSAzureEnvironment]$azureStackEnvironment) {
$armAccessToken = $null
$attempts = 0
$maxAttempts = 12
$delayInSeconds = 5
do {
try {
$attempts++
$armAccessToken = (Get-GraphToken -Resource $azureStackEnvironment.ActiveDirectoryServiceEndpointResourceId -UseEnvironmentData -ErrorAction Stop).access_token
}
catch {
if ($attempts -ge $maxAttempts) {
throw
}
Write-Verbose "Error attempting to acquire ARM access token: $_`r`n$($_.Exception)" -Verbose
Write-Verbose "Delaying for $delayInSeconds seconds before trying again... (attempt $attempts/$maxAttempts)" -Verbose
Start-Sleep -Seconds $delayInSeconds
}
}
while (-not $armAccessToken)
return $armAccessToken
}
$logFile = Join-Path -Path $PSScriptRoot -ChildPath "$DirectoryTenantName.$(Get-Date -Format MM-dd_HH-mm-ss_ms).log"
Write-Verbose "Logging additional information to log file '$logFile'" -Verbose
$logStartMessage = "[$(Get-Date -Format 'hh:mm:ss tt')] - Beginning invocation of '$($MyInvocation.InvocationName)' with parameters: $(ConvertTo-Json $PSBoundParameters -Depth 4)"
$logStartMessage >> $logFile
try {
# Redirect verbose output to a log file
Invoke-Main 4>> $logFile
$logEndMessage = "[$(Get-Date -Format 'hh:mm:ss tt')] - Script completed successfully."
$logEndMessage >> $logFile
}
catch {
$logErrorMessage = "[$(Get-Date -Format 'hh:mm:ss tt')] - Script terminated with error: $_`r`n$($_.Exception)"
$logErrorMessage >> $logFile
Write-Warning "An error has occurred; more information may be found in the log file '$logFile'" -WarningAction Continue
throw
}
}
<#
.Synopsis