azure-powershell icon indicating copy to clipboard operation
azure-powershell copied to clipboard

Timing issue between creation of service principal and delegation on Azure subscription

Open CraigWiand opened this issue 10 years ago • 29 comments

The open source PowerShell script here is used to create an Azure AD Application associate it with a new service principal via New-AzureRmADServicePrincipal and then delegate that service principals rights on a target Azure subscription via New-AzureRMRoleAssignment. I have been able to reproduce a periodic timing issue when running the script where the delegation fails with a “PrincipalNotFound” http REST response. The error is inconstant and if I subsequently re-issue the same command it will succeed. I can provide the output of the Azure PowerShell cmdlets with the addition of -Debug -Verbose to the commands to return the raw REST output (ping me directly internal to MSFT please)

In the results, when https://graph.windows.net/{tenant_id}/$metadata#directoryObjects/Microsoft.DirectoryServices.ServicePrincipal is queried for the service principal, it locates the object and successfully returns attributes "objectId": "e7e918c7-536c-49c1-ac96-f3f80b89bd54". However, when a subsequent call goes to https://management.azure.com//subscriptions/{subscriptionID}/providers/Microsoft.Authorization/roleAssignments that call fails with “Principal e7e918c7536c49c1ac96f3f80b89bd54 does not exist in the directory”.

It is my belief that the graph endpoint the service principal create call is going to may be load balanced to a different backend directory instance than the ARM call is querying and potentially suffering from directory version skew until the replication of the object completes.

CraigWiand avatar May 19 '16 18:05 CraigWiand

Same problem here. I have implemented a (rather ugly) work-around: I try several times until New-AzureRmRoleAssignment succeds:

Function NewAzureRmRoleAssignment($resourceGroupName, $objectId, $roleDefinitionName, $retryCount) {
    $totalRetries = $retryCount
    While ($True) {
        Try {
            $Null = New-AzureRmRoleAssignment -ResourceGroupName $resourceGroupName -ObjectId $objectId -RoleDefinitionName $roleDefinitionName
            Return
        }
        Catch {
            # The principal could not be found. Maybe it was just created.
            If ($retryCount -eq 0) {
                Write-Error "An error occurred: $($_.Exception)`n$($_.ScriptStackTrace)"
                throw "The principal '$objectId' cannot be granted '$roleDefinitionName' role on the resource group '$resourceGroupName'. Please make sure the principal exists and try again later."
            }
            $retryCount--
            Write-Warning "  The principal '$objectId' cannot be granted '$roleDefinitionName' role on the resource group '$resourceGroupName'. Trying again (attempt $($totalRetries - $retryCount)/$totalRetries)"
            Start-Sleep 10
        }
    }
}

In my current environment and script usually the 3rd attempt succeeds (which means I have to wait 20 seconds until the newly created app principal is taken into account).

Of course this behavior brings uncertainty and unnecessary complication to the deployment scripts so seeing it fixed would be a great improvement.

lucmoco avatar Nov 21 '17 13:11 lucmoco

@darshanhs90 Can you take a look at this issue?

CC @cormacpayne

maddieclayton avatar Mar 10 '18 00:03 maddieclayton

Looks like this has to do with the caching withing the service/ARM

darshanhs90 avatar Mar 10 '18 00:03 darshanhs90

I'm facing this too. Do you think having a sleep statement would help?

amoghnatu avatar Jun 21 '18 18:06 amoghnatu

Any luck in getting this issue resolved ? facing the same issue.

kumammanish avatar Sep 05 '18 09:09 kumammanish

Sadly I do not have a great resolution. I believe the issue has also been seen in the cli utility as reported here and there was a PR here. From quick glance it looks like they used a combination of passing the OID instead of the resolved name and doing a sleep if the specific error was returned.

CraigWiand avatar Sep 05 '18 15:09 CraigWiand

Hello @maddieclayton / @darshanhs90 , Is there any update or an ETA for this fix? Currently one of our customer is seeing the same problem even after putting a sleep in the code for 30 seconds! Is there any alternate for this?

Thank you.

amoghnatu avatar Sep 14 '18 10:09 amoghnatu

Running into the same issue using Azure CLI. Any update on this?

syedhassaanahmed avatar Oct 10 '18 20:10 syedhassaanahmed

Same problem with CLI

lukasmrtvy avatar Oct 22 '18 13:10 lukasmrtvy

Same problem with ARM

Shell32-Natsu avatar Feb 01 '19 21:02 Shell32-Natsu

I'm running into the same issue with az cli 2.0.

devlace avatar Feb 06 '19 04:02 devlace

Same problem with ARM

dileep626 avatar Feb 28 '19 10:02 dileep626

do we have a solution yet, this seems a very basic scenario broken right? creating the MSI as the Principle and assign some roles to it.

dawwa avatar Apr 23 '19 22:04 dawwa

Agree, would be very useful if this worked in arm.

alburgin avatar May 04 '19 01:05 alburgin

This issue is very annoying for ARM, @darshanhs90 kindly ping if there is any update here?

gavinfish avatar May 16 '19 03:05 gavinfish

This problem came up recently for me. We have an ARM template with a VM which has an system assigned identity and there's a role assignment from within the template. This was working fine for a couple weeks but recently came up where the role assignment would fail intermittently. In an ARM template it's impossible to place any sleep/retry. I ended up having to deploy the role assignment as a separate template (with retry/sleep), which is ugly.

anhvoms avatar May 16 '19 15:05 anhvoms

Still hitting this in template deployment.

gsingh000 avatar Dec 23 '19 21:12 gsingh000

This has been resolved with the addition of the PrincipalType property on the RoleAssignment, and this functionality is available in ARM templates (https://docs.microsoft.com/bs-latn-ba/azure/role-based-access-control/role-assignments-template#new-service-principal), but now this property needs to be exposed in Poweshell.

kwill-MSFT avatar Jan 27 '20 22:01 kwill-MSFT

What versions of azure cli and powershell cli are needed to pick up this fix, please?

wsupernor avatar Feb 29 '20 02:02 wsupernor

This has been resolved with the addition of the PrincipalType property on the RoleAssignment, and this functionality is available in ARM templates (https://docs.microsoft.com/bs-latn-ba/azure/role-based-access-control/role-assignments-template#new-service-principal), but now this property needs to be exposed in Poweshell.

I was able to update my ARM template to resolve this error but now I get a new error.

The client 'xxf5285b-4e3b-4d7c-9c5b-xxxxx' with object id 'xxf5285b-4e3b-4d7c-9c5b-xxxxx' does not have authorization to perform action 'Microsoft.ContainerInstance/register/action' over scope '/subscriptions/xxd59a98-f6d0-4d81-be04-xxxxx' or the scope is invalid. If access was recently granted, please refresh your credentials.

The principal does have Contributor role.

image

Gist of script at https://gist.githubusercontent.com/indranil-chakraborty-thd/a00fcde354e9baadf9afac3a9b32f3c0/raw/989a4ff614adea8d9d5f704a75dd69f3cfa103a8/azuredeploy.json