Update RegisterWithAzure.psm1 for 1803 release

This commit is contained in:
BradleyBartlett 2018-04-02 11:45:12 -07:00
Родитель 4b1a4ddcc1
Коммит aa502450e4
2 изменённых файлов: 503 добавлений и 225 удалений

Просмотреть файл

@ -2,40 +2,108 @@
The functions in this module allow you to perform the steps of registering your Azure Stack with your Azure subscription. Additional details can be found in the [documentation](https://docs.microsoft.com/en-us/azure/azure-stack/azure-stack-register).
These functions can be run on any machine that can invoke-command on the Privileged Endpoint. As a prerequisite, make sure that you have, and are an owner of, an Azure subscription and that you have installed the correct version of Azure Powershell as outlined here: [Install Powershell for Azure Stack](https://docs.microsoft.com/en-us/azure/azure-stack/azure-stack-powershell-install)
These functions can be run on any machine that has access to the Privileged Endpoint. As a prerequisite, make sure that you have, and are an owner of, an Azure subscription and that you have installed the correct version of Azure Powershell as outlined here: [Install Powershell for Azure Stack](https://docs.microsoft.com/en-us/azure/azure-stack/azure-stack-powershell-install)
Once you have downloaded this module, open an elevated instance of Powershell ISE and run the functions contained:
Once you have downloaded the RegisterWithAzure.psm1 module, open an elevated instance of Powershell ISE and run the functions contained:
To register with Azure and enable marketplace syndication and usage data reporting:
### Import RegisterWithAzure.psm1
To import the RegisterWithAzure.psm1 module, navigate to where the module was downloaded and run the below:
```powershell
Import-Module "<path to RegisterWithAzure.psm1>" -Force -Verbose
Set-AzsRegistration -CloudAdminCredential $cloudAdminCredential -PrivilegedEndpoint $privilegedEndpoint -BillingModel PayAsYouUse
Import-Module .\RegisterWithAzure.psm1 -Force -Verbose
```
## Register in a connected environment
In a connected environment, to register with Azure, allow the download of marketplace items, and start reporting usage data to Azure you must be logged in to the correct Azure Powershell context
### Set the correct Azure Powershell Context
```powershell
Login-AzureRmAccount -Subscription '<Your Azure Subscription>' -Environment '<The Azure Environment where subscription was created>'
```
### Complete registration / activation
Then you must run the below command from RegisterWithAzure.psm1:
```powershell
Set-AzsRegistration -PrivilegedEndpoint "<Computer Name>-ERCS01"
```
## ## Change or remove registration in a disconnected environment
### Remove Registration
To remove the existing registration resource and disable marketplace syndication and usage data reporting:
```powershell
Remove-AzsRegistration -CloudAdminCredential $cloudAdminCredential -PrivilegedEndpoint $privilegedEndpoint
Set-AzsRegistration -PrivilegedEndpoint "<Computer Name>-ERCS01"
```
[!NOTE] You must be logged in to the same Azure Powershell context that you ran Set-AzsRegistration under
### Switch registration to a new subscription
To switch the existing registration to a new subscription or directory:
```powershell
# Remove the existing registration
Remove-AzsRegistration -CloudAdminCredential $cloudAdminCredential -PrivilegedEndpoint $privilegedEndpoint
Remove-AzsRegistration -PrivilegedEndpoint "<Computer Name>-ERCS01"
# Set the Azure Powershell context to the appropriate subscription
Set-AzureRmContext -SubscriptionId "<new subscription to register>"
# Register with the new subscription
Set-AzsRegistration -CloudAdminCredential $cloudAdminCredential -PrivilegedEndpoint $privilegedEndpoint -BillingModel PayAsYouUse
Set-AzsRegistration -PrivilegedEndpoint "<Computer Name>-ERCS01" -BillingModel PayAsYouUse
```
You must be logged into the appropriate Azure Powershell context that you wish to be used for registration of your Azure Stack environment
If you are registering in an internet-disconnected scenario you can run these functions:
## Register in a disconnected environment
If you are registering in an internet-disconnected scenario there are a few more steps to complete registration.
1) Get registration token from Azure Stack
2) Create registration resource in Azure
3) Retrieve activation token from registration resource in Azure
4) Create activation resource in Azure stack
### Get a registration token
You must first retrieve a registration token from the Azure Stack environment
```powershell
# Perform this function on the AzureStack Environment
Get-AzsRegistrationToken -CloudAdminCredential $cloudAdminCredential -PrivilegedEndpoint $PrivilegedEndpoint -BillingModel Development -TokenOutputFilePath "C:\Temp\RegistrationToken.txt"
# Copy the registration token from the TokenOutputFilePath and pass it to this function on the Azure / Internet connected machine
Register-AzsEnvironment -RegistrationToken $yourRegistrationToken
# To UnRegister you must have either the registration token originally used or the registration resource name
UnRegister-AzsEnvironment -RegistrationName "AzureStack-cb1e5061-1d93-4836-81ea-3b74a1db857a"
# Retrieve a registration token and save it to the TokenOutputFilePath
$TokenOutputFilePath = "<file path where token will be saved>"
Get-AzsRegistrationToken -PrivilegedEndpoint "<Computer Name>-ERCS01" -BillingModel Capacity -AgreementNumber '<EA Agreement Number>' -TokenOutputFilePath $TokenOutputFilepath
```
### Create a registration resource in Azure
You must use the registration token created in the step above and perform the below command on a computer connected to public Azure
[!NOTE] Remember to download and import the RegisterWithAzure.psm1 module before running the below commands
```powershell
# Log in to the correct Azure Powershell context
Login-AzureRmAccount -Subscription '<Your Azure Subscription>' -Environment '<The Azure Environment where subscription was created>'
# Create a registration resource in Azure
Register-AzsEnvironment -RegistrationToken "<Registration token text value>"
```
### Retrieve activation key
An activation key is required to create an activation resource in Azure Stack. You can retrieve this from the registration resource in Azure.
Run the below command under the same context as the step above:
```powershell
$KeyOutputFilePath = "<file path where key will be saved>"
Get-AzsActivationKey -RegistrationName "<name of registration resource in Azure>" -KeyOutputFilePath $KeyOutputFilePath
```
### Create activation resource in Azure Stack
The activation key created above must be copied to the Azure Stack environment before registration / activation can be complete.
Run the below commands to complete registration in a disconnected environment:
```powershell
New-AzsActivationResource -PrivilegedEndpoint "<Computer Name>-ERCS01" -ActivationKey "<activation key text value>"
```
Registration and activation is now complete for a disconnected environment. If you need to change or update your registration in a disconnected environment follow the below instructions
## Change or remove registration in a disconnected environment
### Remove activation resource from Azure Stack
You must first remove the activation resource from your Azure Stack
```powershell
Remove-AzsActivationResource -PrivilegedEndpoint "<Computer Name>-ERCS01"
```
### Remove registration resource from Azure
Next you must remove the registration resource from Azure. The below command must be run on a computer with connection to public Azure and be logged in to the correct Azure Powershell context.
You must provide either the registration token or the registration name to the below command:
```powershell
# Use the registration name
UnRegister-AzsEnvironment -RegistrationName "<name of registration resource in Azure>"
# Or use the registration token
UnRegister-AzsEnvironment -RegistrationToken "<original registration token text value>"
```
### Repeat the process for registering in a disconnected environment
Once the above steps are complete you must go through the steps for registering in a disconnected environment but you will need to update parameters on the registration token (if necessary) and ensure
that commands performed on the public Azure connected machine are performed under the new Azure Powershell context.

Просмотреть файл

@ -15,10 +15,10 @@ if (-not (Test-Path $LogFolder))
{
New-Item -Path $LogFolder -ItemType Directory -Force | Out-Null
}
if(-not $Global:AzureRegistrationLog)
if(-not $AzureRegistrationLog)
{
$Global:AzureRegistrationLog = "$LogFolder\AzureStack.AzureRegistration.$(Get-Date -Format yyyy-MM-dd.hh-mm-ss).log"
$null = New-Item -Path $Global:AzureRegistrationLog -ItemType File -Force
$AzureRegistrationLog = "$LogFolder\AzureStack.AzureRegistration.$(Get-Date -Format yyyy-MM-dd.HH-mm-ss).log"
$null = New-Item -Path $AzureRegistrationLog -ItemType File -Force
}
################################################################
@ -54,9 +54,9 @@ This script will create the following resources by default:
See documentation for more detail: https://docs.microsoft.com/en-us/azure/azure-stack/azure-stack-register
.PARAMETER CloudAdminCredential
.PARAMETER PrivilegedEndpointCredential
Powershell object that contains credential information i.e. user name and password.The CloudAdmin has access to the Privileged Endpoint VM (also known as Emergency Console) to call whitelisted cmdlets and scripts.
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
@ -96,25 +96,25 @@ Used when the billing model is set to capacity. You will need to provide a speci
This example registers your AzureStack environment with Azure, enables syndication, and enables usage reporting to Azure.
Set-AzsRegistration -CloudAdminCredential $CloudAdminCredential -PrivilegedEndpoint "Azs-ERCS01"
Set-AzsRegistration -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint "Azs-ERCS01"
.EXAMPLE
This example registers your AzureStack environment with Azure, enables syndication, and disables usage reporting to Azure.
Set-AzsRegistration -CloudAdminCredential $CloudAdminCredential -PrivilegedEndpoint "Azs-ERCS01" -BillingModel 'Capacity' -UsageReportingEnabled:$false -AgreementNumber $MyAgreementNumber
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 -CloudAdminCredential $CloudAdminCredential -PrivilegedEndpoint "Azs-ERCS02" -ResourceGroupName "ContosoStackRegistrations"
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 -CloudAdminCredential $CloudAdminCredential -PrivilegedEndpoint "Azs-ERCS01" -BillingModel Capacity -MarketplaceSyndicationEnabled:$false -UsageReportingEnabled:$false -AgreementNumber $MyAgreementNumber
Set-AzsRegistration -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint "Azs-ERCS01" -BillingModel Capacity -MarketplaceSyndicationEnabled:$false -UsageReportingEnabled:$false -AgreementNumber $MyAgreementNumber
.NOTES
@ -132,7 +132,7 @@ function Set-AzsRegistration{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[PSCredential] $CloudAdminCredential,
[PSCredential] $PrivilegedEndpointCredential,
[Parameter(Mandatory = $true)]
[String] $PrivilegedEndpoint,
@ -172,7 +172,7 @@ function Set-AzsRegistration{
Log-Output "*********************** Begin log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n"
$azureAccountInfo = Get-AzureAccountInfo -AzureContext $AzureContext
$session = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -CloudAdminCredential $CloudAdminCredential -Verbose
$session = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -PrivilegedEndpointCredential $PrivilegedEndpointCredential -Verbose
$stampInfo = Confirm-StampVersion -PSSession $session
$registrationName = "AzureStack-$($stampInfo.CloudID)"
@ -191,18 +191,9 @@ function Set-AzsRegistration{
$registrationToken = Get-RegistrationToken @getTokenParams -Session $session -StampInfo $stampInfo
# Register environment with Azure
if (($AzureContext.Environment.Name -eq 'AzureChinaCloud') -and ($ResourceGroupLocation -ne 'westcentralus'))
{
$CustomResourceGroupLocation = $ResourceGroupLocation
}
elseif ($AzureContext.Environment.Name -eq 'AzureChinaCloud')
{
$CustomResourceGroupLocation = 'ChinaEast'
}
else
{
$CustomResourceGroupLocation = $ResourceGroupLocation
}
# Set resource group location based on environment
$CustomResourceGroupLocation = Set-ResourceGroupLocation -AzureEnvironment $AzureContext.Environment.Name -ResourceGroupLocation $ResourceGroupLocation
New-RegistrationResource -ResourceGroupName $ResourceGroupName -ResourceGroupLocation $CustomResourceGroupLocation -RegistrationToken $RegistrationToken
# Assign custom RBAC role
@ -210,7 +201,7 @@ function Set-AzsRegistration{
New-RBACAssignment -SubscriptionId $AzureContext.Subscription.SubscriptionId -ResourceGroupName $ResourceGroupName -RegistrationName $RegistrationName -ServicePrincipal $servicePrincipal
# Activate AzureStack syndication / usage reporting features
$activationKey = Get-RegistrationActivationKey -ResourceGroupName $ResourceGroupName -RegistrationName $RegistrationName
$activationKey = Get-AzsActivationkey -ResourceGroupName $ResourceGroupName -RegistrationName $RegistrationName
Log-Output "Activating Azure Stack (this may take up to 10 minutes to complete)."
Activate-AzureStack -Session $session -ActivationKey $ActivationKey
@ -232,9 +223,9 @@ Remove-AzsRegistration uses the current Azure Powershell context and runs script
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 CloudAdminCredential
.PARAMETER PrivilegedEndpointCredential
Powershell object that contains credential information i.e. user name and password.The CloudAdmin has access to the JEA Computer (also known as Emergency Console) to call whitelisted cmdlets and scripts.
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
@ -253,7 +244,7 @@ The location where the resource group has been created. Defaults to "westcentral
This example unregisters your AzureStack environment with Azure.
Remove-AzsRegistration -CloudAdminCredential $CloudAdminCredential -PrivilegedEndpoint $PrivilegedEndpoint
Remove-AzsRegistration -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint $PrivilegedEndpoint
.NOTES
@ -264,7 +255,7 @@ function Remove-AzsRegistration{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[PSCredential] $CloudAdminCredential,
[PSCredential] $PrivilegedEndpointCredential,
[Parameter(Mandatory = $true)]
[String] $PrivilegedEndpoint,
@ -290,7 +281,7 @@ function Remove-AzsRegistration{
Log-Output "*********************** Begin log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n"
$azureAccountInfo = Get-AzureAccountInfo -AzureContext $AzureContext
$session = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -CloudAdminCredential $CloudAdminCredential -Verbose
$session = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -PrivilegedEndpointCredential $PrivilegedEndpointCredential -Verbose
$stampInfo = Confirm-StampVersion -PSSession $session
$registrationName = "AzureStack-$($stampInfo.CloudID)"
@ -304,46 +295,8 @@ function Remove-AzsRegistration{
{
Log-Output "Resource found. Deactivating Azure Stack and removing resource: $registrationResourceId"
$BillingModel = $registrationResource.Properties.BillingModel
$AgreementNumber = $registrationResource.Properties.AgreementNumber
# Configure Azure Bridge
$servicePrincipal = New-ServicePrincipal -RefreshToken $azureAccountInfo.Token.RefreshToken -AzureEnvironmentName $AzureContext.Environment.Name -TenantId $azureAccountInfo.TenantId -PSSession $session
# Get registration token
if (($BillingModel -eq "Capacity") -or ($BillingModel -eq "Development"))
{
$getTokenParams = @{
BillingModel = $BillingModel
MarketplaceSyndicationEnabled = $false
UsageReportingEnabled = $false
AgreementNumber = $AgreementNumber
}
}
else
{
$getTokenParams = @{
BillingModel = $BillingModel
MarketplaceSyndicationEnabled = $false
UsageReportingEnabled = $true
}
}
Log-Output "Deactivating syndication features..."
Log-Output "Get-RegistrationToken parameters: $(ConvertTo-Json $getTokenParams)"
$registrationToken = Get-RegistrationToken @getTokenParams -Session $session -StampInfo $stampInfo
# Register environment with Azure
New-RegistrationResource -ResourceGroupName $ResourceGroupName -ResourceGroupLocation $ResourceGroupLocation -RegistrationToken $RegistrationToken
# 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
# Deactivate AzureStack syndication / usage reporting features
$activationKey = Get-RegistrationActivationKey -ResourceGroupName $ResourceGroupName -RegistrationName $RegistrationName
Log-Output "De-Activating Azure Stack (this may take up to 10 minutes to complete)."
Activate-AzureStack -Session $session -ActivationKey $ActivationKey
DeActivate-AzureStack -Session $session
Log-Output "Your environment is now unable to syndicate items and is no longer reporting usage data"
@ -374,9 +327,9 @@ Get-AzsRegistrationToken will use the BillingModel, MarketplaceSyndicationEnable
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 CloudAdminCredential
.PARAMETER PrivilegedEndpointCredential
Powershell object that contains credential information i.e. user name and password.The CloudAdmin has access to the privileged endpoint to call approved cmdlets and scripts.
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
@ -400,21 +353,21 @@ A valid agreement number must be provided if the 'capacity' BillingModel paramet
.EXAMPLE
This example generates a registration token for use in Register-AzsEnvironment and writes it to a txt file.
$registrationToken = Get-AzsRegistrationToken -CloudAdminCredential $cloudAdminCredential -PrivilegedEndpoint $PrivilegedEndpoint -BillingModel Development -TokenOutputFilePath "C:\Temp\RegistrationToken.txt"
$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 -CloudAdminCredential $cloudAdminCredential -PrivilegedEndpoint $PrivilegedEndpoint -BillingModel Development -TokenOutputFilePath "C:\Temp\RegistrationToken.txt"
Register-AzsEnvironment -CloudAdminCredential $cloudAdminCredential -PrivilegedEndpoint $PrivilegedEndpoint -RegistrationToken $registrationToken
$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] $CloudAdminCredential,
[PSCredential] $PrivilegedEndpointCredential,
[Parameter(Mandatory = $true)]
[String] $PrivilegedEndpoint,
@ -459,7 +412,7 @@ Function Get-AzsRegistrationToken{
Log-Output "*********************** Begin log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n"
$params = @{
CloudAdminCredential = $CloudAdminCredential
PrivilegedEndpointCredential = $PrivilegedEndpointCredential
PrivilegedEndpoint = $PrivilegedEndpoint
BillingModel = $BillingModel
MarketplaceSyndicationEnabled = $false
@ -552,18 +505,7 @@ Function Register-AzsEnvironment{
Log-Output "*********************** Begin log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n"
$azureAccountInfo = Get-AzureAccountInfo -AzureContext $AzureContext
if (($AzureContext.Environment.Name -eq 'AzureChinaCloud') -and ($ResourceGroupLocation -ne 'westcentralus'))
{
$CustomResourceGroupLocation = $ResourceGroupLocation
}
elseif ($AzureContext.Environment.Name -eq 'AzureChinaCloud')
{
$CustomResourceGroupLocation = 'ChinaEast'
}
else
{
$CustomResourceGroupLocation = $ResourceGroupLocation
}
$CustomResourceGroupLocation = Set-ResourceGroupLocation -AzureEnvironment $AzureContext.Environment.name -ResourceGroupLocation $ResourceGroupLocation
New-RegistrationResource -ResourceGroupName $ResourceGroupName -ResourceGroupLocation $CustomResourceGroupLocation -RegistrationToken $RegistrationToken
Log-Output "Your Azure Stack environment is now registered with Azure."
@ -690,9 +632,9 @@ Gets the registration name used for registration
The registration name in Azure is derived from the CloudId of the environment: "AzureStack-<CloudId>".
This function gets the CloudId by calling a PEP script and returns the name used during registration
.PARAMETER CloudAdminCredential
.PARAMETER PrivilegedEndpointCredential
Powershell object that contains credential information i.e. user name and password.The CloudAdmin has access to the Privileged Endpoint VM (also known as Emergency Console) to call whitelisted cmdlets and scripts.
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
@ -702,14 +644,14 @@ Privileged Endpoint VM that performs environment administration actions. Also kn
.EXAMPLE
This example returns the name that was used for registration
Get-AzsRegistrationName -CloudAdminCredential $CloudAdminCredential -PrivilegedEndpoint Azs-ERCS01
Get-AzsRegistrationName -PrivilegedEndpointCredential $PrivilegedEndpointCredential -PrivilegedEndpoint Azs-ERCS01
#>
Function Get-AzsRegistrationName{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[PSCredential] $CloudAdminCredential,
[PSCredential] $PrivilegedEndpointCredential,
[Parameter(Mandatory = $true)]
[String] $PrivilegedEndpoint
@ -721,9 +663,225 @@ Function Get-AzsRegistrationName{
$VerbosePreference = [System.Management.Automation.ActionPreference]::Continue
Log-Output "*********************** Begin log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n"
$session = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -CloudAdminCredential $CloudAdminCredential -Verbose
$session = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -PrivilegedEndpointCredential $PrivilegedEndpointCredential -Verbose
$registrationName = Get-RegistrationName -Session $session
Log-Output "*********************** End log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n`r`n"
return $registrationName
}
<#
.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
)
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
$VerbosePreference = [System.Management.Automation.ActionPreference]::Continue
Log-Output "*********************** Begin log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n"
$azureAccountInfo = Get-AzureAccountInfo -AzureContext $AzureContext
$currentAttempt = 0
$maxAttempt = 3
$sleepSeconds = 10
do
{
try
{
Log-Output "Retrieving activation key."
$resourceActionparams = @{
Action = "GetActivationKey"
ResourceName = $RegistrationName
ResourceType = "Microsoft.AzureStack/registrations"
ResourceGroupName = $ResourceGroupName
ApiVersion = "2017-06-01"
}
Log-Output "Getting activation key from $RegistrationName..."
$actionResponse = Invoke-AzureRmResourceAction @resourceActionparams -Force
Log-Output "Activation key successfully retrieved."
if ($KeyOutputFilePath)
{
Log-Output "Activation key will be written to: $KeyOutputFilePath"
$actionResponse.ActivationKey | Out-File $KeyOutputFilePath -Force
}
Log-Output "Your activation key has been collected."
Log-Output "*********************** End log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n`r`n"
return $actionResponse.ActivationKey
}
catch
{
Log-Warning "Retrieval of activation key failed:`r`n$($_)"
Log-Output "Waiting $sleepSeconds seconds and trying again..."
$currentAttempt++
Start-Sleep -Seconds $sleepSeconds
if ($currentAttempt -ge $maxAttempt)
{
Log-Throw -Message $_ -CallingFunction $PSCmdlet.MyInvocation.MyCommand.Name
}
}
} while ($currentAttempt -lt $maxAttempt)
}
<#
.SYNOPSIS
Creates the activation resource in Azure Stack
.DESCRIPTION
Creates an activation resource in Azure Stack in the resource group 'azurestack'. Also configures usage and syndication options.
.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 ActivationKey
The text output of Get-AzsActivationKey. Contains information required to configure Azure Stack registration appropriately.
#>
Function New-AzsActivationResource{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[PSCredential] $PrivilegedEndpointCredential,
[Parameter(Mandatory = $true)]
[String] $PrivilegedEndpoint,
[Parameter(Mandatory = $true)]
[String] $ActivationKey
)
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
$VerbosePreference = [System.Management.Automation.ActionPreference]::Continue
Log-Output "*********************** Begin log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n"
$session = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -PrivilegedEndpointCredential $PrivilegedEndpointCredential -Verbose
Log-Output "Activating Azure Stack (this may take up to 10 minutes to complete)."
Activate-AzureStack -Session $session -ActivationKey $ActivationKey
Log-OutPut "Your environment has finished the registration and activation process."
Log-Output "*********************** End log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n`r`n"
}
<#
.SYNOPSIS
Removes the activation resource created during New-AzsActivationResource
.DESCRIPTION
Prompts the user to log in to the Azure Stack Administrator account, finds and removes the activation resource created
during New-AzsActivationResource. This will remove any downloaded marketplace products.
.PARAMETER AzureStackAdminSubscriptionId
The subscription id of the Azure Stack administrator. This user must have access to the 'marketplace management' blade.
#>
Function Remove-AzsActivationResource{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[PSCredential] $PrivilegedEndpointCredential,
[Parameter(Mandatory = $true)]
[String] $PrivilegedEndpoint,
[Parameter(Mandatory = $false)]
[String] $AzureStackAdminSubscriptionId
)
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
$VerbosePreference = [System.Management.Automation.ActionPreference]::Continue
Log-Output "*********************** Begin log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n"
$session = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -PrivilegedEndpointCredential $PrivilegedEndpointCredential -Verbose
try
{
$AzureStackStampInfo = Invoke-Command -Session $session -ScriptBlock { Get-AzureStackStampInformation }
Login-AzureRmAccount -TenantId $AzureStackStampInfo.AADTenantID -Environment 'AzureStack'
$azureStackContext = Get-AzureRmContext
$azureStackContextDetails = @{
Account = $azureStackContext.Account
Environment = $azureStackContext.Environment
Subscription = $azureStackContext.Subscription
Tenant = $azureStackContext.Tenant
}
Log-Output "Successfully logged into Azure Stack account: $(ConvertTo-Json $azureStackContextDetails)"
if (-not $AzureStackAdminSubscriptionId)
{
$AzureStackAdminSubscriptionId = $azureStackContext.Subscription.Id
}
$activationResource = Get-AzureRmResource -ResourceId "/subscriptions/$AzureStackAdminSubscriptionId/resourceGroups/azurestack-activation/providers/Microsoft.AzureBridge.Admin/activations/default"
Log-Output "Activation resource found: $(ConvertTo-Json $activationResource)"
Remove-AzureRmResource -ResourceId $activationResource.ResourceId -Force
}
catch
{
Log-Throw -Message "An error occurred during removal of the activation resource in Azure Stack: `r`n$_" -CallingFunction $PSCmdlet.MyInvocation.MyCommand.Name
}
finally
{
if ($session)
{
$session | Remove-PSSession
}
}
Log-Output "Activation resource has been removed from Azure Stack."
Log-Output "*********************** End log: $($PSCmdlet.MyInvocation.MyCommand.Name) ***********************`r`n`r`n"
}
#endregion
@ -784,7 +942,7 @@ Function Get-RegistrationToken{
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[PSCredential] $CloudAdminCredential,
[PSCredential] $PrivilegedEndpointCredential,
[Parameter(Mandatory = $false)]
[String] $PrivilegedEndpoint,
@ -820,7 +978,7 @@ Function Get-RegistrationToken{
if (-not $session)
{
$sessionProvided = $false
$session = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -CloudAdminCredential $CloudAdminCredential -Verbose
$session = Initialize-PrivilegedEndpointSession -PrivilegedEndpoint $PrivilegedEndpoint -PrivilegedEndpointCredential $PrivilegedEndpointCredential -Verbose
}
if (-not $StampInfo)
@ -937,6 +1095,8 @@ function New-RegistrationResource{
}
} while ($currentAttempt -lt $maxAttempt)
$resourceCreationParams['Location'] = 'Global'
do
{
try
@ -963,59 +1123,6 @@ function New-RegistrationResource{
<#
.SYNOPSIS
Retrieves the ActivationKey from the registration resource created during Register-AzsEnvironment
#>
Function Get-RegistrationActivationKey{
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[String] $ResourceGroupName = 'azurestack',
[Parameter(Mandatory = $false)]
[String] $RegistrationName
)
$currentAttempt = 0
$maxAttempt = 3
$sleepSeconds = 10
do
{
try
{
Log-Output "Retrieving activation key."
$resourceActionparams = @{
Action = "GetActivationKey"
ResourceName = $RegistrationName
ResourceType = "Microsoft.AzureStack/registrations"
ResourceGroupName = $ResourceGroupName
ApiVersion = "2017-06-01"
}
Log-Output "Getting activation key from $RegistrationName..."
$actionResponse = Invoke-AzureRmResourceAction @resourceActionparams -Force
Log-Output "Activation key successfully retrieved."
return $actionResponse.ActivationKey
}
catch
{
Log-Warning "Retrieval of activation key failed:`r`n$($_)"
Log-Output "Waiting $sleepSeconds seconds and trying again..."
$currentAttempt++
Start-Sleep -Seconds $sleepSeconds
if ($currentAttempt -ge $maxAttempt)
{
Log-Throw -Message $_ -CallingFunction $PSCmdlet.MyInvocation.MyCommand.Name
}
}
} while ($currentAttempt -lt $maxAttempt)
}
<#
.SYNOPSIS
Configures bridge from AzureStack to Azure through use of a service principal.
#>
@ -1069,66 +1176,66 @@ Adds the provided subscription id to the custom RBAC role 'Registration Reader'
#>
function New-RBACAssignment{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[String] $RegistrationName,
[Parameter(Mandatory = $true)]
[String] $ResourceGroupName,
[Parameter(Mandatory = $true)]
[String] $SubscriptionId,
[Parameter(Mandatory = $true)]
[Object] $ServicePrincipal
)
$currentAttempt = 0
$maxAttempt = 3
$sleepSeconds = 10
do
{
try
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[String] $RegistrationName,
[Parameter(Mandatory = $true)]
[String] $ResourceGroupName,
[Parameter(Mandatory = $true)]
[String] $SubscriptionId,
[Parameter(Mandatory = $true)]
[Object] $ServicePrincipal
)
$currentAttempt = 0
$maxAttempt = 3
$sleepSeconds = 10
do
{
$registrationResource = Get-AzureRmResource -ResourceId "/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroupName/providers/Microsoft.AzureStack/registrations/$RegistrationName"
$RoleAssigned = $false
$RoleName = "Azure Stack Registration Owner"
Log-Output "Setting $RoleName role on '$($RegistrationResource.ResourceId)'"
# Determine if RBAC role has been assigned
$roleAssignmentScope = "/subscriptions/$($RegistrationResource.SubscriptionId)/resourceGroups/$($RegistrationResource.ResourceGroupName)/providers/Microsoft.AzureStack/registrations/$($RegistrationResource.ResourceName)"
$roleAssignments = Get-AzureRmRoleAssignment -Scope $roleAssignmentScope -ObjectId $ServicePrincipal.ObjectId
foreach ($role in $roleAssignments)
try
{
if ($role.RoleDefinitionName -eq $RoleName)
$registrationResource = Get-AzureRmResource -ResourceId "/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroupName/providers/Microsoft.AzureStack/registrations/$RegistrationName"
$RoleAssigned = $false
$RoleName = "Azure Stack Registration Owner"
Log-Output "Setting $RoleName role on '$($RegistrationResource.ResourceId)'"
# Determine if RBAC role has been assigned
$roleAssignmentScope = "/subscriptions/$($RegistrationResource.SubscriptionId)/resourceGroups/$($RegistrationResource.ResourceGroupName)/providers/Microsoft.AzureStack/registrations/$($RegistrationResource.ResourceName)"
$roleAssignments = Get-AzureRmRoleAssignment -Scope $roleAssignmentScope -ObjectId $ServicePrincipal.ObjectId
foreach ($role in $roleAssignments)
{
$RoleAssigned = $true
if ($role.RoleDefinitionName -eq $RoleName)
{
$RoleAssigned = $true
}
}
if (-not $RoleAssigned)
{
New-AzureRmRoleAssignment -Scope $roleAssignmentScope -RoleDefinitionName $RoleName -ObjectId $ServicePrincipal.ObjectId
}
break
}
catch
{
Log-Warning "Assignment of custom RBAC Role $RoleName failed:`r`n$($_)"
Log-Output "Waiting $sleepSeconds seconds and trying again..."
$currentAttempt++
Start-Sleep -Seconds $sleepSeconds
if ($currentAttempt -ge $maxAttempt)
{
Log-Throw -Message $_ -CallingFunction $PSCmdlet.MyInvocation.MyCommand.Name
}
}
if (-not $RoleAssigned)
{
New-AzureRmRoleAssignment -Scope $roleAssignmentScope -RoleDefinitionName $RoleName -ObjectId $ServicePrincipal.ObjectId
}
break
}
catch
{
Log-Warning "Assignment of custom RBAC Role $RoleName failed:`r`n$($_)"
Log-Output "Waiting $sleepSeconds seconds and trying again..."
$currentAttempt++
Start-Sleep -Seconds $sleepSeconds
if ($currentAttempt -ge $maxAttempt)
{
Log-Throw -Message $_ -CallingFunction $PSCmdlet.MyInvocation.MyCommand.Name
}
}
} while ($currentAttempt -lt $maxAttempt)
}
} while ($currentAttempt -lt $maxAttempt)
}
<#
@ -1175,6 +1282,44 @@ function Activate-AzureStack{
.SYNOPSIS
DeActivates features in AzureStack
#>
function DeActivate-AzureStack{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[System.Management.Automation.Runspaces.PSSession] $Session
)
$currentAttempt = 0
$maxAttempt = 3
$sleepSeconds = 10
do
{
try
{
$activation = Invoke-Command -Session $session -ScriptBlock { Remove-AzureStackActivation }
break
}
catch
{
Log-Warning "DeActivation of Azure Stack features failed:`r`n$($_)"
Log-Output "Waiting $sleepSeconds seconds and trying again..."
$currentAttempt++
Start-Sleep -Seconds $sleepSeconds
if ($currentAttempt -ge $maxAttempt)
{
Log-Throw -Message $_ -CallingFunction $PSCmdlet.MyInvocation.MyCommand.Name
}
}
} while ($currentAttempt -lt $maxAttempt)
}
<#
.SYNOPSIS
Gathers required data from current Azure Powershell context
#>
@ -1195,6 +1340,14 @@ function Get-AzureAccountInfo{
Tenant = $AzureContext.Tenant
}
if (($AzureContext.Environment.name -ne 'AzureChinaCloud') -or ($AzureContext.Environment.name -ne 'AzureUsGovernment'))
{
if ($AzureContext.Environment.name -ne 'AzureCloud')
{
Log-Throw "The provided Azure Environment is not supported for registration: $($AzureContext.Environment.name )" -CallingFunction $PSCmdlet.MyInvocation.MyCommand.Name
}
}
if (-not($AzureContext.Subscription))
{
Log-Output "Current Azure context:`r`n$(ConvertTo-Json $azureContextDetails)"
@ -1246,7 +1399,7 @@ function Initialize-PrivilegedEndpointSession{
[String] $PrivilegedEndpoint,
[Parameter(Mandatory=$true)]
[PSCredential] $CloudAdminCredential
[PSCredential] $PrivilegedEndpointCredential
)
$currentAttempt = 0
@ -1257,7 +1410,7 @@ function Initialize-PrivilegedEndpointSession{
try
{
Log-Output "Initializing session with privileged endpoint: $PrivilegedEndpoint. Attempt $currentAttempt of $maxAttempt"
$session = New-PSSession -ComputerName $PrivilegedEndpoint -ConfigurationName PrivilegedEndpoint -Credential $CloudAdminCredential
$session = New-PSSession -ComputerName $PrivilegedEndpoint -ConfigurationName PrivilegedEndpoint -Credential $PrivilegedEndpointCredential
Log-Output "Connection to $PrivilegedEndpoint successful"
return $session
}
@ -1394,6 +1547,60 @@ function Confirm-StampVersion{
.SYNOPSIS
Sets the resource group location based on the current AzureContext Environment name
#>
function Set-ResourceGroupLocation{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string] $AzureEnvironment,
[Parameter(Mandatory=$false)]
[string] $ResourceGroupLocation
)
if ($AzureEnvironment -eq 'AzureCloud')
{
if ($ResourceGroupLocation -ne 'westcentralus')
{
$CustomResourceGroupLocation = $ResourceGroupLocation
}
else
{
$CustomResourceGroupLocation = 'westcentralus'
}
}
elseif ($AzureEnvironment -eq 'AzureChinaCloud')
{
if ($ResourceGroupLocation -ne 'westcentralus')
{
$CustomResourceGroupLocation = $ResourceGroupLocation
}
else
{
$CustomResourceGroupLocation = 'ChinaEast'
}
}
elseif ($AzureEnvironment -eq 'AzureUSGovernment')
{
if ($ResourceGroupLocation -ne 'westcentralus')
{
$CustomResourceGroupLocation = $ResourceGroupLocation
}
else
{
$CustomResourceGroupLocation = 'usdodeast'
}
}
return $CustomResourceGroupLocation
}
<#
.SYNOPSIS
Appends the text passed in to a log file and writes the verbose stream to the console.
#>
@ -1404,7 +1611,7 @@ function Log-Output{
[object] $Message
)
"$(Get-Date -Format yyyy-MM-dd.hh-mm-ss): $Message" | Out-File $Global:AzureRegistrationLog -Append
"$(Get-Date -Format yyyy-MM-dd.hh-mm-ss): $Message" | Out-File $AzureRegistrationLog -Append
Write-Verbose "$(Get-Date -Format yyyy-MM-dd.hh-mm-ss): $Message"
}
@ -1424,7 +1631,7 @@ function Log-Warning{
# Write Error: line seperately otherwise out message will not contain stack trace
Log-Output "*** WARNING ***"
"$(Get-Date -Format yyyy-MM-dd.hh-mm-ss): $Message" | Out-File $Global:AzureRegistrationLog -Append
"$(Get-Date -Format yyyy-MM-dd.hh-mm-ss): $Message" | Out-File $AzureRegistrationLog -Append
Write-Warning "$(Get-Date -Format yyyy-MM-dd.hh-mm-ss): $Message"
Log-Output "*** End WARNING ***"
}
@ -1449,7 +1656,7 @@ function Log-Throw{
$errorLine = "************************ Error ************************"
# Write Error line seperately otherwise out message will not contain stack trace
"$(Get-Date -Format yyyy-MM-dd.hh-mm-ss): $errorLine" | Out-File $Global:AzureRegistrationLog -Append
"$(Get-Date -Format yyyy-MM-dd.hh-mm-ss): $errorLine" | Out-File $AzureRegistrationLog -Append
Write-Verbose "$(Get-Date -Format yyyy-MM-dd.hh-mm-ss): $errorLine"
Log-Output $Message
@ -1457,8 +1664,8 @@ function Log-Throw{
Log-OutPut "*********************** Ending registration action during $CallingFunction ***********************`r`n"
"$(Get-Date -Format yyyy-MM-dd.hh-mm-ss): Logs can be found at: $Global:AzureRegistrationLog and \\$PrivilegedEndpoint\c$\maslogs `r`n" | Out-File $Global:AzureRegistrationLog -Append
Write-Verbose "$(Get-Date -Format yyyy-MM-dd.hh-mm-ss): Logs can be found at: $Global:AzureRegistrationLog and \\$PrivilegedEndpoint\c$\maslogs `r`n"
"$(Get-Date -Format yyyy-MM-dd.hh-mm-ss): Logs can be found at: $AzureRegistrationLog and \\$PrivilegedEndpoint\c$\maslogs `r`n" | Out-File $AzureRegistrationLog -Append
Write-Verbose "$(Get-Date -Format yyyy-MM-dd.hh-mm-ss): Logs can be found at: $AzureRegistrationLog and \\$PrivilegedEndpoint\c$\maslogs `r`n"
throw $Message
}
@ -1469,6 +1676,9 @@ function Log-Throw{
Export-ModuleMember Get-AzsRegistrationToken
Export-ModuleMember Register-AzsEnvironment
Export-ModuleMember Unregister-AzsEnvironment
Export-ModuleMember Get-AzsActivationKey
Export-ModuleMember New-AzsActivationResource
Export-ModuleMember Remove-AzsActivationResource
Export-ModuleMember Get-AzsRegistrationName
# Connected functions