pythonazure-functionsazure-storageazure-python-sdkazure-resource-lock

How to lock storage accounts in Azure using Python SDK


I am using python SDK to lock a particular azure resource. Although I found documentation, I am getting exceptions as a resource not found while I am trying to lock the storage account.

As I am trying to store accounts in a Resource Grp, I'm using the below functionality.

I initiated Managementlockclient and ResourceManagementClient.

lockclient = ManagementLockClient( credential=credential,
                subscription_id=subscriptionid
)

lockclient.management_locks.create_or_update_at_resource_level() 

Apart from the above, is there any other way to lock all storage accounts in a resource group? I know we have a functionality to lock all resources in an RG using create_or_update_at_resource_group_level but I only want to lock storage accounts. So I am using create_or_update_at_resource_level.

Can anyone please help?

Image

Response : <class 'azure.core.exceptions.ResourceNotFoundError'> occurred.


Solution

  • I tried in my environment and got below results:

    Trying to lock particular storage account resource

    You can use create_or_update_by_scope method to create lock by using scopes of storage account.

    You can get the scope of storage account through portal.

    Portal -> storage account -> endpoint -> resource id -> copy-resource-id.

    Portal: enter image description here

    Code: The below code is used to create lock under scope with DefaultAzureCredential and ManagementLockClient.

    from azure.mgmt.resource import ManagementLockClient
    from azure.identity import DefaultAzureCredential
    
    
    subscriptionid = "<subscription-id>"
    credential = DefaultAzureCredential()
    lockclient = ManagementLockClient( credential=credential,subscription_id=subscriptionid)
    lockclient.management_locks.create_or_update_by_scope(scope="/subscriptions/sub-id/resourceGroups/v-venkat-rg/providers/Microsoft.Storage/storageAccounts/venkat326",
          lock_name="demolock",parameters={"level":"CanNotDelete"},content_type = "application/json")
    print("Lock created")
    

    Console:

    enter image description here

    Portal:

    enter image description here