pythonazureazure-resource-lock

How to lock all resources in an Azure Resource group using Python


I am using azure SDK python to lock all resources in a specific resource group. I am not able to find proper help/documentation for the same.

There are no methods related to this in the azure-mgmt-resource package

Can anyone suggest any?


Solution

  • You will need to instantiate a ManagementLockClient object, then call the create_or_update_at_resource_group_level method to create the CanNotDelete lock at resource group level.

    We can apply the lock at resource group level, because all child resources inherit the same lock from the parent scope.

    Demo

    from azure.common.client_factory import get_client_from_cli_profile
    from azure.mgmt.resource import ResourceManagementClient, ManagementLockClient
    
    # Authenticate with Azure CLI credentials
    client = get_client_from_cli_profile(ResourceManagementClient)
    
    resource_group_name = "myResourceGroup"
    
    # Ensure resource group exists
    if client.resource_groups.check_existence(resource_group_name):
    
        # Create lock client to do lock operations
        lock_client = get_client_from_cli_profile(ManagementLockClient)
    
        # Add delete lock at resource group level
        lock_client.management_locks.create_or_update_at_resource_group_level(
            resource_group_name=resource_group_name,
            lock_name="DeleteLock",
            parameters={"level": "CanNotDelete"},
        )
    else:
        print(
            f"Resource group {resource_group_name} does not exist in your subscription!"
        )