For a given Azure subscription I want to assign custom role to Service Principal. In order to achieve this, I first check if the custom role definition exists in the subscription. If the role does not exists I update the role definition's assignable scope to include this subscription. I am facing 'RoleDefinitionDoesNotExist' error intermittently when I try to assign role. How do I fix this?
My code:
$roleDef = Get-AzureRmRoleDefinition -Name $azureRmRole
if($roleDef -eq $null)
{
Select-AzureRmSubscription -SubscriptionName $prodSubscription
#Role definition exists in $prodSubscription
$newRole = Get-AzureRmRoleDefinition -Name $azureRmRole
#$scope = '/subscriptions/xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx'
$newRole.AssignableScopes.Add($scope)
$def = Set-AzureRmRoleDefinition -Role $newRole
# I have verified that role definition is updated
}
Select-AzureRmSubscription -SubscriptionName $SubscriptionName
New-AzureRmRoleAssignment -RoleDefinitionName $azureRmRole -ObjectId $SPNid -Scope $scope
Error:
New-AzureRmRoleAssignment : The specified role definition with ID 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx' does not exist. At C:\Untitled1.ps1:71 char:1 + New-AzureRmRoleAssignment -RoleDefinitionName $azureRmRole -ObjectId ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [New-AzureRmRoleAssignment], CloudException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Resources.NewAzureRoleAssignmentCommand

New-AzureRmRoleDefinitionto create a custom role. - Shui shengbao$azureRmRolethe vaule is your custom Name. In my example, the name isVirtual Machine Power Manager, do you sure it exist? - Shui shengbao