azurepowershellazure-runbookazure-resource-groupazure-resource-lock

Azure Automation - Unable to Remove-AzResourceLock


I have an issue deleting an Azure Lock, at the resource group level. I am doing it from an Azure Runbook.

I authenticate fine (I am able to Get details of whatever I want). Here's the code for that:

# Ensures you do not inherit an AzureRMContext in your runbook
Disable-AzContextAutosave –Scope Process
"Logging in to Azure..."
$connection = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzAccount -ServicePrincipal -Tenant $connection.TenantID -ApplicationId $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint

And if I do, say, Get-AzResource -ResourceGroupName $RG, I get the info I need. But the problem is that I actually need to delete some resources of that resource group, and it has a lock.

When I Remove-AzResourceLock -LockId $getAzureLock.LockId -Force, I am thrown this:

Remove-AzResourceLock : AuthorizationFailed : The client XX with object id XX does not have authorization to perform action 'Microsoft.Authorization/locks/delete' over scope '/subscriptions/<redacted>/resourceGroups/<redacted>/providers/Microsoft.Authorization/locks/resourceDellock' or the scope is invalid. If access was recently granted, please refresh your credentials.

FYI, I've redacted the subscription/object id information.

For the life of me, I am not able to get around it. The application is added as a Contributor at the subscription level, from Access Control (IAM).

I have tried so many things, that I am just to tired to write down! I am sorry. The last 4 hours I've been reading and trying stuffs. So pardon me!

Please, help me get around this..


Solution

  • As per the documentation, only Owner and User Access Administrator built-in roles have the permission to delete a lock and not the Contributor role.

    Deletes the management lock of a resource or any level below the resource. To delete management locks, you must have access to Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access Administrator are granted those actions.

    So your solution would be to either grant Owner/User Access Administrator role to your service principal or create a custom role and grant appropriate permissions on Microsoft.Authorization/* actions.