Skip to content

Instantly share code, notes, and snippets.

@johlju
Last active August 13, 2017 08:34
Show Gist options
  • Save johlju/301490cc813e4b490a3cecc1f010d921 to your computer and use it in GitHub Desktop.
Save johlju/301490cc813e4b490a3cecc1f010d921 to your computer and use it in GitHub Desktop.
New-AzureServicePrincipal
<#
.SYNOPSIS
New-AzureServicePrincipal
.DESCRIPTION
This task creates an Azure Service Principal in Azure AD that will be used for all installation automation.
This can only be run interactively as the Login-AzureRmAccount will pop up an interactive window for
the user to log in with.
The output of this task can be used to deploy the application in future and should be stored in each contributors AppVeyor account.
#>
[CmdletBinding()]
param
(
[Parameter()]
[System.String]
$Name = 'DSCConfigurationTest',
[Parameter(Mandatory = $true)]
[System.String]
$SubscriptionId,
[Parameter(Mandatory = $true)]
[System.String]
$ADDomain,
[Parameter(Mandatory = $true)]
[System.Management.Automation.PSCredential]
$ApplicationPassword
)
if ($SubscriptionId)
{
$account = Login-AzureRmAccount -SubscriptionId $SubscriptionId
}
else
{
$account = Login-AzureRmAccount
}
Write-Host -Object "Creating '$Name' Service Principal in Azure AD"
$app = New-AzureRmADApplication `
-DisplayName $Name `
-HomePage "https://$ADDomain/$Name" `
-IdentifierUris "https://$ADDomain/$Name" `
-Password $ApplicationPassword.GetNetworkCredential().Password
Write-Host -Object "Creating Azure AD Service Principal for ApplicationId '$($app.ApplicationId)'"
$null = New-AzureRmADServicePrincipal `
-ApplicationId $app.ApplicationId
Write-Host -Object "Assigning role Contributor to AD Service Principal for ApplicationId '$($app.ApplicationId)'"
$roleAssignment = $null
$retryCount = 0
while (-not $roleAssignment -and ($retryCount -lt 10))
{
try
{
$roleAssignment = New-AzureRmRoleAssignment `
-RoleDefinitionName Contributor `
-ServicePrincipalName $app.ApplicationId `
-ErrorAction SilentlyContinue
}
catch
{
Write-Host -Object "Error assigning role Contributor to AD Service Principal for ApplicationId '$($app.ApplicationId)'. Retrying in 5 seconds..."
Start-Sleep -Seconds 5
$retryCount++
}
} # while
if (-not $roleAssignment)
{
Write-Error -Message "Failed assigning role Contributor to AD Service Principal for ApplicationId '$($app.ApplicationId)'."
return
}
Write-Host -Object "'$Name' service principal has been created."
Write-Host -Object "ApplicationID is '$($app.ApplicationId)'."
Write-Host -Object "SubscriptionID is '$SubscriptionId'."
Write-Host -Object "TenantID of '$($account.Context.Tenant.Id)'."
return [PSObject] @{
ApplicationID = $app.ApplicationId
SubscriptionID = $SubscriptionId
TenantID = $account.Context.Tenant.Id
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment