I'm working on a powershell script that will create a Resource Group, register the included application (in this example, a Web Api) to the associated AAD.
But, when calling trying to assign Reader
rights, it keeps on failing.
I've started from the basic deploy*.ps1 file that comes with the AzureResourceGroup template in Visual Studio (2015).
I'm running the following code:
#Requires -Version 3.0
#Requires -Module AzureRM.Resources
#Requires -Module Azure.Storage
Import-Module Azure -ErrorAction SilentlyContinue
Set-StrictMode -Version 3
Login-AzureRmAccount
$tenantWebSite = New-AzureRmADApplication -DisplayName "TheSiteName" -HomePage "http://MySignOnUrl" -IdentifierUris "http://MyIdentifierUrl" -Password "MyClientSecret"
$tenantWebSiteServicePrincipal = New-AzureRmADServicePrincipal -ApplicationId $tenantWebSite.ApplicationId
New-AzureRmRoleAssignment -RoleDefinitionName Reader -ServicePrincipalName $tenantWebSite.ApplicationId
That last command (New-AzureRmRoleAssignment
) keeps on failing with the following error:
09:58:26 - [ERROR] New-AzureRmRoleAssignment : PrincipalNotFound: Principal
09:58:26 - [ERROR] 50f3d430c68b485b8c11a63552171550 does not exist in the directory
09:58:26 - [ERROR] <MyTenantId>.
09:58:26 - [ERROR] At D:\dev_new_2010\cto\src\dev\d.tom.0\deploy\calidos.maat.deploy.azureresource
09:58:26 - [ERROR] group\Scripts\Deploy-AzureResourceGroup.ps1:115 char:1
09:58:26 - [ERROR] + New-AzureRmRoleAssignment -RoleDefinitionName Reader -ServicePrincipa ...
09:58:26 - [ERROR] + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
09:58:26 - [ERROR] + CategoryInfo : CloseError: (:) [New-AzureRmRoleAssignment], Clo
09:58:26 - [ERROR] udException
09:58:26 - [ERROR] + FullyQualifiedErrorId : Microsoft.Azure.Commands.Resources.NewAzureRoleA
09:58:26 - [ERROR] ssignmentCommand
Normally, I run this script by using the deploy option in visual studio. When I run this script from a Microsoft Azure PowerShell
command window, I get the same error.
BUT, when I run the exact command in that same powershell window, it works!
New-AzureRmRoleAssignment -RoleDefinitionName Reader -ServicePrincipalName <ApplicationId>
Does anybody have an idea on why this would fail from within the ps1-file? I've also tried to explicitly define the scope, but that didn't do the trick either.
EDIT:
Ok, the previous "solution" was pure luck... Apparently, the New-AzureRmADServicePrincipal
is created asynchronously. That method does immediately return an object, but the actual principal isn't created immediately...
I worked around this by adding a Start-Sleep -s 15
command.
If this isn't enough, either increase it, or catch the error and wait another few seconds before trying again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With