'Error creating role assignment using Azure REST API - Principal does not exist in the directory

I'm trying to use the Azure REST api to create role assignments, but it's giving an error:
Exception: {"error":{"code":"PrincipalNotFound","message":"Principal 83ad8925d1714aa380a8555cec2d400c does not exist in the directory ####-####-####"}}

            var url = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments/{Guid.NewGuid()}?api-version=2015-07-01";
            object payload = new
            {
                properties = new
                {
                    roleDefinitionId = role.id,
                    principalId
                }
            };
            await PutAsync<object>(url, payload);

Switching the API version to 2018-09-01-preview does not prevent the issue from occurring.

Related links



Solution 1:[1]

Seems to be an issue caused by replication delay on Microsoft's side.
Attempting to create the role assignment right after creating the security group principal can sometimes result in this error.

I resolved this by just putting my API call in a try-catch with 20 retries with a 20 second delay between each attempt. Eventually it just succeeds.

Note that the error message provided by the API doesn't contain the hyphens/dashes in the GUID, this does NOT mean you passed a bad GUID, the error message is just misleading.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TeamDman