/
RegisterWithAzure.psm1
2062 lines (1603 loc) · 78.1 KB
/
RegisterWithAzure.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.
<#
This module contains functions for registering your environment and enabling marketplace syndication / usage reporting.
To run registration and activation functions you must have a public Azure subscription of any type.
You must also have access to an account / directory that is an owner or contributor to that subscription.
#>
[String]$azureResourceApiVersion = "2017-06-01"
function Initialize-AzureRmEnvironment{
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[String] $Name = 'CustomCloud',
[Parameter(Mandatory=$true, ParameterSetName='CloudManifest')]
[String] $CloudManifestFilePath,
[Parameter(Mandatory=$true, ParameterSetName='CloudARMEndpoint')]
[String] $CloudARMEndpoint
)
if ( $PSCmdlet.ParameterSetName -eq 'CloudManifest' ){
$cloudJson = Get-Content $CloudManifestFilePath -Raw | ConvertFrom-Json
$cloudJsonContent = $cloudJson.DeploymentData
$CloudARMEndpoint = $cloudJsonContent.CustomEnvironmentEndpoints.CustomCloudARMEndpoint
}
$fullUri = $CloudARMEndpoint.TrimEnd('/')+"/metadata/endpoints?api-version=2015-01-01"
$response = Invoke-RestMethod -Uri $fullUri -ErrorAction Stop -UseBasicParsing -TimeoutSec 30 -Verbose
Write-Verbose -Message "Endpoints: $(ConvertTo-Json $response)" -Verbose
$endpoints = @{
ActiveDirectoryAuthority = $response.authentication.loginEndpoint.TrimEnd('/') + "/"
ActiveDirectoryServiceEndpointResourceId = $response.authentication.audiences[0]
ResourceManagerUrl = $CloudARMEndpoint
GalleryUrl = $response.galleryEndpoint
GraphUrl = $response.graphEndpoint
GraphEndpointResourceId = $response.graphEndpoint
EnableAdfsAuthentication = $true
}
Remove-AzureRMEnvironment -Name $Name -ErrorAction Ignore | Out-Null
Add-AzureRmEnvironment -Name $Name @endpoints | Out-Null
$azureEnvironment = Get-AzureRmEnvironment -Name $Name -ErrorAction Stop
return $azureEnvironment
}
# Generate log file(s)
function New-RegistrationLogFile
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[String] $LogDate = (Get-Date -Format yyyy-MM-dd),
[Parameter(Mandatory=$false)]
[String] $RegistrationFunction = 'RegistrationOperation'
)
# Create log folder
$LogFolder = "$env:SystemDrive\MASLogs\Registration"
if (-not (Test-Path $LogFolder -PathType Container))
{
New-Item -Path $LogFolder -ItemType Directory -Force | Out-Null
}
$logFilePath = "$LogFolder\AzureStack.Activation.$RegistrationFunction-$LogDate.log"
Write-Verbose "Writing logs to file: $logFilePath"
if (-not (Test-Path $logFilePath -PathType Leaf))
{
$null = New-Item -Path $logFilePath -ItemType File -Force
}
$Script:registrationLog = $logFilePath
}
function Initialize-RegistrationLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[String] $RegistrationFunction = 'RegistrationOperation',
[Parameter(Mandatory=$false)]
[switch] $SkipIfExists
)
$Script:ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
$Script:VerbosePreference = [System.Management.Automation.ActionPreference]::Continue
if (-not ($SkipIfExists -and $Script:registrationLog)) {
New-RegistrationLogFile -RegistrationFunction $RegistrationFunction
Log-Output "*********************** Begin log: $RegistrationFunction ***********************`r`n"
}
}
################################################################
# Core Functions
################################################################
#region CoreFunctions
#region ConnectedScenario
function Get-RegistrationDetailsConnected {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[PSCredential] $PrivilegedEndpointCredential,
[Parameter(Mandatory = $true)]
[String] $PrivilegedEndpoint,
[Parameter(Mandatory = $false)]
[ValidateNotNullorEmpty()]
[PSObject] $AzureContext = (Get-AzureRmContext),
[Parameter(Mandatory = $false)]
[PSCredential] $AzureStackAdminCredential
)
$session = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -PrivilegedEndpointCredential $PrivilegedEndpointCredential -Verbose
$stampInfo = Confirm-StampVersion -PSSession $session
try {
$envName = "AzureStackAdminReg"
Log-Output "Adding $envName environment using ARMEndpoint: $($stampInfo.AdminExternalEndpoints.AdminResourceManager)"
Remove-AzureRmEnvironment -Name $envName -ErrorAction Ignore | Out-Null
Add-AzureRmEnvironment -Name $envName -ARMEndpoint $stampInfo.AdminExternalEndpoints.AdminResourceManager | Out-Null
$loginParams = @{
Environment = $envName
Tenant = $stampInfo.AADTenantID
Subscription = 'Default Provider Subscription'
}
if ($AzureStackAdminCredential) { $loginParams += @{ Credential = $AzureStackAdminCredential } }
Login-AzureRMAccount @loginParams
$subscription = (Get-AzureRmContext).Subscription.Id
Log-Output "Getting existing registration properties from AzureStack"
$regPropertiesAzureStack = (Get-AzureRmResource -ResourceId "/subscriptions/${subscription}/resourceGroups/azurestack-activation/providers/Microsoft.AzureBridge.Admin/activations/default").Properties
Log-Output "Existing registration properties from AzureStack: $($regPropertiesAzureStack | ConvertTo-Json -Depth 2)"
$marketplaceSyndicationEnabled = $regPropertiesAzureStack.marketplaceSyndicationEnabled
$usageReportingEnabled = $regPropertiesAzureStack.usageReportingEnabled
$azureRegResIden = $regPropertiesAzureStack.azureRegistrationResourceIdentifier
$strArr = $azureRegResIden.Split('/')
$azureSubscription = $strArr[$strArr.IndexOf('subscriptions')+1]
} catch {
Log-Throw "Unable to retrieve registration details from AzureStack `r`n$($_)" -CallingFunction $($PSCmdlet.MyInvocation.MyCommand.Name)
}
try {
$azureContextDetails = @{
Account = $AzureContext.Account
Environment = $AzureContext.Environment
Subscription = $AzureContext.Subscription
Tenant = $AzureContext.Tenant
}
Log-Output "Setting context back to Azure: $($azureContextDetails | ConvertTo-Json -Depth 2)"
Set-AzureRmContext -Context $AzureContext
if ($AzureContext.Subscription.Id -ne $azureSubscription) {
Log-Output "Trying to switch to correct Azure Subscription $azureSubscription for registration"
Set-AzureRmContext -Subscription $azureSubscription
Log-Output "Updating AzureContext to use correct subscription $azureSubscription for registration"
$AzureContext = (Get-AzureRmContext)
}
Log-Output "Getting existing registration resource from Azure"
$regResourceAzure = Get-AzureRmResource -ResourceId $azureRegResIden -ApiVersion $azureResourceApiVersion
Log-Output "Existing registration resource in Azure: $($regResourceAzure | ConvertTo-Json -Depth 2)"
$registrationName = $regResourceAzure.Name
$resourceGroupName = $regResourceAzure.ResourceGroupName
$resourceGroup = Get-AzureRmResourceGroup -Name $resourceGroupName
Log-Output "Existing resource group in Azure: $($resourceGroup | ConvertTo-Json -Depth 2)"
$resourceGroupLocation = $resourceGroup.Location
$billingModel = $regResourceAzure.Properties.billingModel
} catch {
Log-Throw "Unable to retrieve registration details from Azure `r`n$($_)" -CallingFunction $($PSCmdlet.MyInvocation.MyCommand.Name)
}
return @{
PrivilegedEndpointSession = $session
StampInfo = $stampInfo
AzureContext = $AzureContext
RegistrationName = $registrationName
ResourceGroupName = $resourceGroupName
ResourceGroupLocation = $resourceGroupLocation
BillingModel = $billingModel
MarketplaceSyndicationEnabled = $marketplaceSyndicationEnabled
UsageReportingEnabled = $usageReportingEnabled
}
}
<#
.SYNOPSIS
Set-AzsRegistration can be used to register Azure Stack with Azure and enable/disable marketplace syndication and usage reporting.
To run this function, you must have a public Azure subscription of any type.
You must also be logged in to Azure Powershell with an account that is an owner or contributor to that subscription.
.DESCRIPTION
Set-AzsRegistration uses the current Azure Powershell context and runs scripts already present in Azure Stack from the ERCS VM to connect your Azure Stack to Azure.
You MUST be logged in to the Azure Powershell context that you want to register your Azure Stack with.
After connecting with Azure, you can download products from the marketplace (See the documentation for more information: https://docs.microsoft.com/en-us/azure/azure-stack/azure-stack-download-azure-marketplace-item).
Running this script with default parameters will enable marketplace syndication and usage data will default to being reported to Azure.
NOTE: Default billing model is 'Development' and is only usable for proof of concept builds.
To disable syndication or usage reporting see examples below.
This script will create the following resources by default:
- A service principal to perform resource actions
- A resource group in Azure (if needed)
- A registration resource in the created resource group in Azure
- An activation resource group and resource in Azure Stack
See documentation for more detail: https://docs.microsoft.com/en-us/azure/azure-stack/azure-stack-register
.PARAMETER PrivilegedEndpointCredential
Powershell object that contains credential information i.e. user name and password. The Azure Stack administrator has access to the Privileged Endpoint VM (also known as Emergency Console) to call whitelisted cmdlets and scripts.
If not supplied script will request manual input of username and password
.PARAMETER PrivilegedEndpoint
Privileged Endpoint VM that performs environment administration actions. Also known as Emergency Console VM.(Example: AzS-ERCS01 for the ASDK)
.PARAMETER RegistrationName
The name of the registration resource to be created in Azure. A unique name is highly encouraged for those registering multiple environments.
.PARAMETER ResourceGroupName
This will be the name of the resource group in Azure where the registration resource is stored. Defaults to "azurestack"
.PARAMETER ResourceGroupLocation
The location where the resource group will be created. Defaults to "westcentralus"
.PARAMETER BillingModel
The billing model that the subscription uses. Select from "Capacity","PayAsYouUse", and "Development". Defaults to "Development" which is usable for POC installments.
Please see documentation for more information: https://docs.microsoft.com/en-us/azure/azure-stack/azure-stack-billing-and-chargeback
.PARAMETER MarketplaceSyndicationEnabled
This is a switch that determines if this registration will allow you to download products from the Azure Marketplace. Defaults to $true
.PARAMETER UsageReportingEnabled
This is a switch that determines if usage records are reported to Azure. Defaults to $true. Note: This cannot be disabled with billing model set to PayAsYouUse.
.PARAMETER AgreementNumber
Used when the billing model is set to capacity. You will need to provide a specific agreement number associated with your billing agreement.
.PARAMETER MsAssetTag
Used when the billing model is set to custom. You will need to provide a specific MsAssetTag associated with your billing model.
.PARAMETER AzureStackAdminCredential
Azure Stack admin credential used to access admin portal resources
.PARAMETER Reregister
Switch parameter used for re-registration scenario
.EXAMPLE
This example registers your AzureStack environment with Azure, enables syndication, and enables usage reporting to Azure.
Set-AzsRegistration -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint "Azs-ERCS01"
.EXAMPLE
This example registers your AzureStack environment with Azure, enables syndication, and enables usage reporting to Azure, and supplies a custom name.
Set-AzsRegistration -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint "Azs-ERCS01" -RegistrationName "AzsRegistration-TestEnvironment"
.EXAMPLE
This example registers your AzureStack environment with Azure, enables syndication, and disables usage reporting to Azure.
Set-AzsRegistration -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint "Azs-ERCS01" -BillingModel 'Capacity' -UsageReportingEnabled:$false -AgreementNumber $MyAgreementNumber
.EXAMPLE
This example registers your AzureStack environment with Azure, enables syndication and usage and gives a specific name to the resource group
Set-AzsRegistration -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint "Azs-ERCS02" -ResourceGroupName "ContosoStackRegistrations"
.EXAMPLE
This example disables syndication and disables usage reporting to Azure. Note that usage will still be collected, just not sent to Azure.
Set-AzsRegistration -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint "Azs-ERCS01" -BillingModel Capacity -MarketplaceSyndicationEnabled:$false -UsageReportingEnabled:$false -AgreementNumber $MyAgreementNumber
.EXAMPLE
This example re-registers your AzureStack environment to Azure using existing registration details
Set-AzsRegistration -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint "Azs-ERCS01" -AzureStackAdminCredential $AzureStackAdminCredential -Reregister
.NOTES
If you would like to un-Register with Azure by turning off marketplace syndication, disabling usage reporting, and removing the registration resource from Azure you can run Remove-AzsRegistration.
Note that this will remove any downloaded marketplace products.
If you would like to use a different subscription for registration you must first run Remove-AzsRegistration followed by Set-AzsRegistration after logging into the appropriate Azure Powershell context.
This will remove any downloaded marketplace products and they will need to be re-downloaded.
You MUST be logged in to Azure before attempting to use Set-AzsRegistration.
It is very important to ensure you are logged in to the correct Azure Account in Powershell before running this function.
#>
function Set-AzsRegistration{
[CmdletBinding(DefaultParameterSetName='Register')]
param(
[Parameter(Mandatory = $true)]
[PSCredential] $PrivilegedEndpointCredential,
[Parameter(Mandatory = $true)]
[String] $PrivilegedEndpoint,
[Parameter(Mandatory = $true, ParameterSetName = "Register")]
[String] $RegistrationName,
[Parameter(Mandatory = $false)]
[ValidateNotNullorEmpty()]
[PSObject] $AzureContext = (Get-AzureRmContext),
[Parameter(Mandatory = $false, ParameterSetName = "Register")]
[String] $ResourceGroupName = 'azurestack',
[Parameter(Mandatory = $false, ParameterSetName = "Register")]
[String] $ResourceGroupLocation = (Get-DefaultResourceGroupLocation -AzureContext $AzureContext),
[Parameter(Mandatory = $false, ParameterSetName = "Register")]
[ValidateSet('Capacity', 'PayAsYouUse', 'Development', 'Custom', 'Ruggedized')]
[string] $BillingModel = 'Development',
[Parameter(Mandatory = $false, ParameterSetName = "Register")]
[switch] $MarketplaceSyndicationEnabled = $true,
[Parameter(Mandatory = $false, ParameterSetName = "Register")]
[switch] $UsageReportingEnabled = @{'Capacity'=$false;
'PayAsYouUse'=$true;
'Development'=$true;
'Custom'=$false;
'Ruggedized'=$true;}[$BillingModel],
[Parameter(Mandatory = $false)]
[ValidateNotNull()]
[string] $AgreementNumber,
[Parameter(Mandatory=$false)]
[ValidateNotNull()]
[string] $MsAssetTag,
[Parameter(Mandatory = $false, ParameterSetName = "Reregister")]
[PSCredential] $AzureStackAdminCredential,
[Parameter(Mandatory = $true, ParameterSetName = "Reregister")]
[switch] $Reregister
)
Initialize-RegistrationLog -RegistrationFunction $PSCmdlet.MyInvocation.MyCommand.Name
Validate-AzureContext -AzureContext $AzureContext
$privilegedEndpointSession = $null
$stampInfo = $null
if ($Reregister) {
$params = Get-RegistrationDetailsConnected -PrivilegedEndpointCredential $PrivilegedEndpointCredential `
-PrivilegedEndpoint $PrivilegedEndpoint `
-AzureContext $AzureContext `
-AzureStackAdminCredential $AzureStackAdminCredential
$privilegedEndpointSession = $params.PrivilegedEndpointSession
$stampInfo = $params.StampInfo
$AzureContext = $params.AzureContext
$RegistrationName = $params.RegistrationName
$ResourceGroupName = $params.ResourceGroupName
$ResourceGroupLocation = $params.ResourceGroupLocation
$BillingModel = $params.BillingModel
$MarketplaceSyndicationEnabled = $params.MarketplaceSyndicationEnabled
$UsageReportingEnabled = $params.UsageReportingEnabled
Log-Output "Retrieved registration details: RegistrationName = $RegistrationName, ResourceGroupName = $ResourceGroupName, `
ResourceGroupLocation = $ResourceGroupLocation, BillingModel = $BillingModel, `
MarketplaceSyndicationEnabled = $MarketplaceSyndicationEnabled, UsageReportingEnabled = $UsageReportingEnabled"
}
Validate-ResourceGroupLocation -ResourceGroupLocation $ResourceGroupLocation
Validate-BillingModel -BillingModel $BillingModel -MsAssetTag $MsAssetTag
$azureAccountInfo = Get-AzureAccountInfo -AzureContext $AzureContext
try {
if (-not $privilegedEndpointSession) {
$privilegedEndpointSession = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -PrivilegedEndpointCredential $PrivilegedEndpointCredential -Verbose
$stampInfo = Confirm-StampVersion -PSSession $privilegedEndpointSession
}
# Configure Azure Bridge
$servicePrincipal = New-ServicePrincipal -RefreshToken $azureAccountInfo.Token.RefreshToken -AzureEnvironmentName $AzureContext.Environment.Name -TenantId $azureAccountInfo.TenantId -PSSession $privilegedEndpointSession
# Get registration token
$getTokenParams = @{
BillingModel = $BillingModel
MarketplaceSyndicationEnabled = $MarketplaceSyndicationEnabled
UsageReportingEnabled = $UsageReportingEnabled
AgreementNumber = $AgreementNumber
MsAssetTag = $MsAssetTag
TokenVersion = Get-RegistrationTokenVersion -AzureContext $AzureContext
}
Log-Output "Get-RegistrationToken parameters: $(ConvertTo-Json $getTokenParams)"
$registrationToken = Get-RegistrationToken @getTokenParams -Session $PrivilegedEndpointSession -StampInfo $stampInfo
# Register environment with Azure
Log-Output "Creating registration resource at ResourceGroupLocation: $ResourceGroupLocation"
New-RegistrationResource -ResourceGroupName $ResourceGroupName -ResourceGroupLocation $ResourceGroupLocation -RegistrationToken $RegistrationToken -RegistrationName $RegistrationName
# Assign custom RBAC role
Log-Output "Assigning custom RBAC role to resource $RegistrationName"
New-RBACAssignment -SubscriptionId $AzureContext.Subscription.SubscriptionId -ResourceGroupName $ResourceGroupName -RegistrationName $RegistrationName -ServicePrincipal $servicePrincipal
# Activate AzureStack syndication / usage reporting features
$activationKey = Get-AzsActivationkey -ResourceGroupName $ResourceGroupName -RegistrationName $RegistrationName -ConnectedScenario
Log-Output "Activating Azure Stack (this may take up to 10 minutes to complete)."
Activate-AzureStack -Session $PrivilegedEndpointSession -ActivationKey $ActivationKey
} finally {
if ($privilegedEndpointSession) {
Log-OutPut "Removing any existing PSSession..."
$privilegedEndpointSession | Remove-PSSession
}
}
Log-Output "Your environment is now registered and activated using the provided parameters."
Log-Output "*********************** End log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n`r`n"
}
<#
.SYNOPSIS
Remove-AzsRegistration can be used to disable syndication, disable usage reporting, and unregister your environment with Azure.
To run this function, you must have previously run Set-AzsRegistration
You must also be logged in to Azure Powershell with an account that is an owner or contributor to that subscription.
.DESCRIPTION
Remove-AzsRegistration uses the current Azure Powershell context and runs scripts already present in Azure Stack from the ERCS VM to remove a current registration from Azure.
You MUST be logged in to the Azure Powershell context that you want to disassociate your environment from.
You must have already run Set-AzsRegistration before running this function.
.PARAMETER PrivilegedEndpointCredential
Powershell object that contains credential information i.e. user name and password. The Azure Stack administrator has access to the JEA Computer (also known as Emergency Console) to call whitelisted cmdlets and scripts.
If not supplied script will request manual input of username and password
.PARAMETER PrivilegedEndpoint
Privileged Endpoint VM that performs environment administration actions. Also known as Emergency Console VM.(Example: AzS-ERCS01 for the ASDK)
.PARAMETER ResourceGroupName
This is the name of the resource group in Azure where the registration resource has been created. Defaults to "azurestack"
.PARAMETER RegistrationName
The name of the registration resource that was created in Azure. If you have a unique name you should supply it here for removing registration.
.EXAMPLE
This example unregisters your AzureStack environment with Azure.
Remove-AzsRegistration -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint $PrivilegedEndpoint
.EXAMPLE
This example unregisters your AzureStack environment with Azure by pointing to a specific registration
Remove-AzsRegistration -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint $PrivilegedEndpoint -RegistrationName "AzsRegistration-TestEnvironment"
.NOTES
It is very important to ensure you are logged in to the correct Azure Account in Powershell before running this function.
#>
function Remove-AzsRegistration{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[PSCredential] $PrivilegedEndpointCredential,
[Parameter(Mandatory = $true)]
[String] $PrivilegedEndpoint,
[Parameter(Mandatory = $true)]
[String] $RegistrationName,
[Parameter(Mandatory = $false)]
[String] $ResourceGroupName = 'azurestack',
[Parameter(Mandatory = $false)]
[ValidateNotNullorEmpty()]
[PSObject] $AzureContext = (Get-AzureRmContext)
)
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
$VerbosePreference = [System.Management.Automation.ActionPreference]::Continue
New-RegistrationLogFile -RegistrationFunction $PSCmdlet.MyInvocation.MyCommand.Name
Log-Output "*********************** Begin log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n"
Validate-AzureContext -AzureContext $AzureContext
$azureAccountInfo = Get-AzureAccountInfo -AzureContext $AzureContext
try
{
$session = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -PrivilegedEndpointCredential $PrivilegedEndpointCredential -Verbose
$stampInfo = Confirm-StampVersion -PSSession $session
# Find registration resource in Azure
Log-Output "Searching for registration resource in Azure..."
$registrationResource = $null
$registrationResourceId = "/subscriptions/$($AzureContext.Subscription.SubscriptionId)/resourceGroups/$ResourceGroupName/providers/Microsoft.AzureStack/registrations/$registrationName"
$registrationResource = Get-AzureRmResource -ResourceId $registrationResourceId -ApiVersion $azureResourceApiVersion -ErrorAction Ignore
if ($registrationResource.Properties.cloudId -eq $stampInfo.CloudId)
{
Log-Output "Registration resource found: $($registrationResource.ResourceId)"
}
else
{
Log-Throw "The registration resource found does not correlate the current environment's Cloud-Id. `r`nEnvironment Cloud Id: $($stampinfo.CloudId) `r`nResource Cloud Id: $($registrationResource.Properties.cloudId)" -CallingFunction $($PSCmdlet.MyInvocation.MyCommand.Name)
}
if ($registrationResource)
{
Log-Output "Resource found. Deactivating Azure Stack and removing resource: $($registrationResource.ResourceId)"
Log-Output "De-Activating Azure Stack (this may take up to 10 minutes to complete)."
DeActivate-AzureStack -Session $session
Log-Output "Your environment is now unable to syndicate items and is no longer reporting usage data"
# Remove registration resource from Azure
Log-Output "Removing registration resource from Azure..."
Remove-RegistrationResource -ResourceId $registrationResource.ResourceId -ResourceGroupName $ResourceGroupName
}
else
{
Log-Throw -Message "Registration resource with matching CloudId property $($stampInfo.CloudId) was not found. Please ensure a registration resource exists in the provided subscription & resource group." -CallingFunction $($PSCmdlet.MyInvocation.MyCommand.Name)
}
}
finally
{
if ($session)
{
Log-OutPut "Removing any existing PSSession..."
$session | Remove-PSSession
}
}
Log-Output "*********************** End log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n`r`n"
}
#endregion
#region DisconnectedScenario
<#
.SYNOPSIS
Get-AzsRegistrationToken will generate a registration token from the input parameters.
.DESCRIPTION
Get-AzsRegistrationToken will use the BillingModel, MarketplaceSyndicationEnabled, UsageReportingEnabled, and AgreementNumber (if necessary) parameters to generate a registration token.
This token is used to enable / disable Azure Stack features such as Azure marketplace product syndication and Azure Stack usage reporting.
A registration token is required to call Register-AzsEnvironment.
.PARAMETER PrivilegedEndpointCredential
Powershell object that contains credential information i.e. user name and password.The Azure Stack administrator has access to the privileged endpoint to call approved cmdlets and scripts.
This parameter is mandatory and if not supplied then this function will request manual input of username and password
.PARAMETER PrivilegedEndpoint
The name of the VM that has permissions to perform approved powershell cmdlets and scripts. Usually has a name in the format of <ComputerName>-ERCSxx where <ComputerName>
is the name of the machine and ERCS is followed by a number between 01 and 03. Example: Azs-ERCS01 (from the ASDK)
.PARAMETER TokenOutputFilePath
This parameter sets the output location for the registration token.
.PARAMETER BillingModel
The billing model that will be used for this environment. Select from "Capacity", and "Development". Defaults to "Development" which is usable for POC / ASDK installments.
Please see documentation for more information: https://docs.microsoft.com/en-us/azure/azure-stack/azure-stack-billing-and-chargeback
.PARAMETER AgreementNumber
A valid agreement number must be provided if the 'capacity' BillingModel parameter is provided.
.EXAMPLE
This example generates a registration token for use in Register-AzsEnvironment and writes it to a txt file.
$registrationToken = Get-AzsRegistrationToken -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint $PrivilegedEndpoint -BillingModel Development -TokenOutputFilePath "C:\Temp\RegistrationToken.txt"
.NOTES
This function is designed to only be used in conjunction with Register-AzsEnvironment. This will not enable any Azure Stack marketplace syndication or usage reporting features. Example:
$registrationToken = Get-AzsRegistrationToken -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint $PrivilegedEndpoint -BillingModel Development -TokenOutputFilePath "C:\Temp\RegistrationToken.txt"
Register-AzsEnvironment -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint $PrivilegedEndpoint -RegistrationToken $registrationToken
#>
Function Get-AzsRegistrationToken{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[PSCredential] $PrivilegedEndpointCredential,
[Parameter(Mandatory = $true)]
[String] $PrivilegedEndpoint,
[Parameter(Mandatory = $true)]
[ValidateSet('Capacity', 'Development','Custom')]
[string] $BillingModel = 'Capacity',
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[String] $TokenOutputFilePath,
[Parameter(Mandatory = $false)]
[Switch] $UsageReportingEnabled = $false,
[Parameter(Mandatory = $false)]
[Switch] $MarketplaceSyndicationEnabled = $false,
[Parameter(Mandatory = $false)]
[ValidateNotNull()]
[string] $AgreementNumber,
[Parameter(Mandatory=$false)]
[ValidateNotNull()]
[string] $MsAssetTag
)
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
$VerbosePreference = [System.Management.Automation.ActionPreference]::Continue
New-RegistrationLogFile -RegistrationFunction $PSCmdlet.MyInvocation.MyCommand.Name
Validate-BillingModel -BillingModel $BillingModel -MsAssetTag $MsAssetTag
if ($TokenOutputFilePath -and (-not (Test-Path -Path $TokenOutputFilePath -PathType Leaf)))
{
Log-Warning "Provided value for -TokenOutputFilePath does not exist. attempting to create file at $TokenOutputFilePath..."
try
{
New-Item -Path $TokenOutputFilePath -ItemType File -Verbose
Log-Output "File created at path: $TokenOutputFilePath"
}
catch
{
Log-Throw -Message "Unable to create file at location $TokenOutputFilePath. Please provide a valid input for -TokenOutputFilePath. `r`n$($_)" -CallingFunction $($PSCmdlet.MyInvocation.MyCommand.Name)
}
}
Log-Output "*********************** Begin log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n"
$params = @{
PrivilegedEndpointCredential = $PrivilegedEndpointCredential
PrivilegedEndpoint = $PrivilegedEndpoint
BillingModel = $BillingModel
MarketplaceSyndicationEnabled = $MarketplaceSyndicationEnabled
UsageReportingEnabled = $UsageReportingEnabled
AgreementNumber = $AgreementNumber
TokenOutputFilePath = $TokenOutputFilePath
MsAssetTag = $MsAssetTag
}
Log-Output "Registration action params: $(ConvertTo-Json $params)"
try
{
$session = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -PrivilegedEndpointCredential $PrivilegedEndpointCredential -Verbose
$registrationToken = Get-RegistrationToken @params -Session $session
}
finally
{
if ($session)
{
Log-OutPut "Removing any existing PSSession..."
$session | Remove-PSSession
}
}
if ($TokenOutputFilePath)
{
Log-Output "Your registration token can be found at: $TokenOutputFilePath"
}
Log-Output "*********************** End log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n`r`n"
return $registrationToken
}
<#
.SYNOPSIS
Register-AzsEnvironment will register your environment with Azure but will not enable syndication or usage reporting. This can be run on any computer with a connection to the internet.
.DESCRIPTION
Register-AzsEnvironment creates a resource group and registration resource in Azure.
A registration token is required to register with Azure.
.PARAMETER RegistrationToken
The registration token created after running Get-AzsRegistrationToken. This contains BillingModel, marketplace syndication, and other important information.
.PARAMETER AzureEnvironmentName
The Azure environment that will be used to create registration resource. defaults to AzureCloud
.PARAMETER ResourceGroupName
The name of the resource group that will contain the registration resource. Defaults to 'azurestack'
.PARAMETER ResourceGroupLocation
The Azure location where the registration resource group will be created. Defaults to 'westcentralus'
.PARAMETER RegistrationName
The name of the registration resource to be created in Azure. A unique name is highly encouraged for those registering multiple environments.
.EXAMPLE
This example will register your Azure Stack environment with all default parameters.
Register-AzsEnvironment -RegistrationToken $registrationToken
.EXAMPLE
This example will register your Azure Stack environment with a specific name for a resource group
Register-AzsEnvironment -RegistrationToken $registrationToken -ResourceGroupName "ContosoRegistrations"
.EXAMPLE
This example will register your Azure Stack environment with a specific name for the registration resource
Register-AzsEnvironment -RegistrationToken $registrationToken -RegistrationName "AzsRegistration-TestEnvironment"
.NOTES
This function will not enable marketplace syndication or usage reporting.
#>
Function Register-AzsEnvironment{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[ValidateNotNull()]
[String] $RegistrationToken,
[Parameter(Mandatory = $true)]
[String] $RegistrationName,
[Parameter(Mandatory = $false)]
[ValidateNotNullorEmpty()]
[PSObject] $AzureContext = (Get-AzureRmContext),
[Parameter(Mandatory = $false)]
[String] $ResourceGroupName = 'azurestack',
[Parameter(Mandatory = $false)]
[String] $ResourceGroupLocation = (Get-DefaultResourceGroupLocation -AzureContext $AzureContext)
)
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
$VerbosePreference = [System.Management.Automation.ActionPreference]::Continue
New-RegistrationLogFile -RegistrationFunction $PSCmdlet.MyInvocation.MyCommand.Name
Log-Output "*********************** Begin log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n"
Validate-AzureContext -AzureContext $AzureContext
Validate-ResourceGroupLocation -ResourceGroupLocation $ResourceGroupLocation
$azureAccountInfo = Get-AzureAccountInfo -AzureContext $AzureContext
New-RegistrationResource -ResourceGroupName $ResourceGroupName -ResourceGroupLocation $ResourceGroupLocation -RegistrationToken $RegistrationToken -RegistrationName $RegistrationName
Log-Output "Your Azure Stack environment is now registered with Azure."
Log-Output "*********************** End log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n`r`n"
}
<#
.SYNOPSIS
UnRegister-AzsEnvironment will unregister your environment with Azure
.DESCRIPTION
UnRegister-AzsEnvironment removes the registration resource that was created in Azure during Register-AzsEnvironment
.PARAMETER RegistrationToken
The registration token created after running Get-AzsRegistrationToken. This contains information used to find the registration name
.PARAMETER RegistrationName
The name of the registration resource that was created during Register-AzsEnvironment.
.PARAMETER AzureEnvironmentName
The Azure environment that was used to create registration resource. defaults to AzureCloud
.PARAMETER ResourceGroupName
The name of the resource group that was created for the registration resource. Defaults to 'azurestack'
.EXAMPLE
This example will unregister your Azure Stack environment using a registration token
UnRegister-AzsEnvironment -RegistrationToken $registrationToken
.EXAMPLE
This exmple will unregister your Azure Stack environment using the registration name.
UnRegister-AzsEnvironment -RegistrationName "AzsRegistration-TestEnvironment"
.NOTES
This should only be used if Register-AzsEnvironment was called previously. If you would like to disable syndication or usage reporting
that was enabled during Set-AzsRegistration, then you will need to run Remove-AzsRegistration
#>
Function UnRegister-AzsEnvironment{
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[ValidateNotNullorEmpty()]
[PSObject] $AzureContext = (Get-AzureRmContext),
[Parameter(Mandatory = $false)]
[ValidateNotNull()]
[String] $RegistrationToken,
[Parameter(Mandatory = $false)]
[String] $RegistrationName,
[Parameter(Mandatory = $false)]
[String] $ResourceGroupName = 'azurestack',
[Parameter(Mandatory = $false)]
[String] $CloudId
)
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
$VerbosePreference = [System.Management.Automation.ActionPreference]::Continue
New-RegistrationLogFile -RegistrationFunction $PSCmdlet.MyInvocation.MyCommand.Name
Log-Output "*********************** Begin log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n"
Validate-AzureContext -AzureContext $AzureContext
if ((-not $RegistrationToken) -and (-not $CloudId))
{
if (-not $RegistrationName)
{
Log-Throw "Unable to find registration resource with the given parameters. Please provide one of the following: RegistrationName, RegistrationToken, or CloudId" -CallingFunction $($PSCmdlet.MyInvocation.MyCommand.Name)
}
}
if ($RegistrationToken)
{
# Get CloudId from registration token
try
{
$bytes = [System.Convert]::FromBase64String($RegistrationToken)
$tokenObject = [System.Text.Encoding]::UTF8.GetString($bytes) | ConvertFrom-Json
$CloudId = $tokenObject.CloudId
}
Catch
{
Log-Warning "Unable to extract CloudId from provided registration token. Please confirm the input text for the token is correct."
}
}
$azureAccountInfo = Get-AzureAccountInfo -AzureContext $AzureContext
# Find registration resource in Azure
Log-Output "Searching for registration resource in Azure..."
$registrationResource = $null
if ($RegistrationName)
{
$registrationResourceId = "/subscriptions/$($AzureContext.Subscription.SubscriptionId)/resourceGroups/$ResourceGroupName/providers/Microsoft.AzureStack/registrations/$registrationName"
$registrationResource = Get-AzureRmResource -ResourceId $registrationResourceId -ApiVersion $azureResourceApiVersion -ErrorAction Ignore
}
elseif ($CloudId)
{
Log-Output "Parameter 'RegistrationName' not supplied. Searching through all registration resources under current context."
try
{
Log-Output "Attempting to retrieve resources using command: 'Find-AzureRmResource -ResourceType Microsoft.AzureStack/registrations -ResourceGroupNameEquals $ResourceGroupName'"
$registrationResources = Find-AzureRmResource -ResourceType Microsoft.AzureStack/registrations -ResourceGroupNameEquals $ResourceGroupName
}
catch
{
Log-Warning "Could not retrieve resources from Azure `r`n$($_)"
}
if ($registrationResources.Count -eq 0)
{
try
{
Log-Output "Attempting to retrieve resources using command: 'Get-AzureRmResource -ResourceType microsoft.azurestack/registrations -ResourceGroupName $ResourceGroupName'"
$registrationresources = Get-AzureRmResource -ResourceType microsoft.azurestack/registrations -ResourceGroupName $ResourceGroupName -ApiVersion $azureResourceApiVersion
}
catch
{
Log-Throw "Unable to retrieve registration resource(s) from Azure `r`n$($_)" -CallingFunction $($PSCmdlet.MyInvocation.MyCommand.Name)
}
}
Log-Output "Found $($registrationResources.Count) registration resources. Finding a matching CloudId may take some time."
foreach ($resource in $registrationResources)
{
$resourceObject = Get-AzureRmResource -ResourceId "/subscriptions/$($AzureContext.Subscription.SubscriptionId)/resourceGroups/$ResourceGroupName/providers/Microsoft.AzureStack/registrations/$($resource.name)" -ApiVersion $azureResourceApiVersion
$resourceCloudId = $resourceObject.Properties.CloudId
if ($resourceCloudId -eq $stampInfo.CloudId)
{
$registrationResource = $resourceObject
break
}
}
}
if ($registrationResource)
{
Log-Output "Found registration resource in Azure: $($registrationResource.ResourceId)"
Log-Output "Removing registration resource from Azure..."
Remove-RegistrationResource -ResourceId $registrationResource.ResourceId -ResourceGroupName $ResourceGroupName
}
else
{
Log-Throw "Registration resource not found in Azure with the provided parameters. `r`nPlease ensure a valid registration exists in the subscription / resource group provided." -CallingFunction $($PSCmdlet.MyInvocation.MyCommand.Name)
}
Log-Output "Your Azure Stack environment is now unregistered from Azure."
Log-Output "*********************** End log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n`r`n"
}
<#
.SYNOPSIS
Retrieves the ActivationKey from the registration resource created during Register-AzsEnvironment
.DESCRIPTION
This gets an activation key with details on the parameters and environment information from the registration resource.
The activation key is used to create an activation record in AzureStack.
.PARAMETER RegistrationName
The neame of the registration resource created in Azure.
.PARAMETER ResourceGroupName
The name of the resource group where the registration resource was created.
#>
Function Get-AzsActivationKey{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String] $RegistrationName,
[Parameter(Mandatory = $false)]
[ValidateNotNullorEmpty()]
[PSObject] $AzureContext = (Get-AzureRmContext),
[Parameter(Mandatory = $false)]
[String] $ResourceGroupName = 'azurestack',
[Parameter(Mandatory = $false)]
[String] $KeyOutputFilePath,
[Parameter(Mandatory = $false)]
[Switch] $ConnectedScenario
)