From e5e637afa357c4bee594b3cfc12d30f270833f5a Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Thu, 9 Dec 2021 12:43:15 -0800 Subject: [PATCH] Ensure ownership grant (#3173) The focus of these changes is to ensure that the service principal is explicitly granted the "Owner" role on the active resource group, whether the principal was newly created or a cached instance was used. Co-authored-by: Jesse Squire --- .../TestResources/New-TestResources.ps1 | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/eng/common/TestResources/New-TestResources.ps1 b/eng/common/TestResources/New-TestResources.ps1 index d36693ef9..914f68d9a 100644 --- a/eng/common/TestResources/New-TestResources.ps1 +++ b/eng/common/TestResources/New-TestResources.ps1 @@ -580,14 +580,18 @@ try { $PSBoundParameters['TestApplicationOid'] = $TestApplicationOid $PSBoundParameters['TestApplicationSecret'] = $TestApplicationSecret - # Grant the test service principal ownership over the resource group. This may fail if the provisioner is a - # service principal without permissions to grant RBAC roles to other service principals. That should not be - # considered a critical failure, as the test application may have subscription-level permissions and not require - # the explicit grant. - # - # Ignore this check if $AzureTestPrincipal is specified as role assignment will already have been attempted on a - # previous run, and these error messages can be misleading for local runs. - if (!$resourceGroupRoleAssigned -and !$AzureTestPrincipal) { + # If the role hasn't been explicitly assigned to the resource group and a cached service principal is in use, + # query to see if the grant is needed. + if (!$resourceGroupRoleAssigned -and $AzureTestPrincipal) { + $roleAssignment = Get-AzRoleAssignment -ObjectId $AzureTestPrincipal.Id -RoleDefinitionName 'Owner' -ResourceGroupName "$ResourceGroupName" -ErrorAction SilentlyContinue + $resourceGroupRoleAssigned = ($roleAssignment.RoleDefinitionName -eq 'Owner') + } + + # If needed, grant the test service principal ownership over the resource group. This may fail if the provisioner + # is a service principal without permissions to grant RBAC roles to other service principals. That should not be + # considered a critical failure, as the test application may have subscription-level permissions and not require + # the explicit grant. + if (!$resourceGroupRoleAssigned) { Log "Attempting to assigning the 'Owner' role for '$ResourceGroupName' to the Test Application '$TestApplicationId'" $principalOwnerAssignment = New-AzRoleAssignment -RoleDefinitionName "Owner" -ApplicationId "$TestApplicationId" -ResourceGroupName "$ResourceGroupName" -ErrorAction SilentlyContinue