List and manage Azure Resource Locks with Python SDK

Question:

I am trying to list and loop through Azure Resource Locks of a resource group by using Python SDK.

    from azure.mgmt.resource.locks.v2016_09_01.aio import ManagementLockClient
    management_lock_client = ManagementLockClient(credential, subscription.subscription_id)
    locks = management_lock_client.management_locks.list_at_resource_group_level(resource__group_snapshot)
    for lock in locks:
        management_lock_client.management_locks.delete(resource__group_snapshot, lock.name)

But here, I get the error:

for lock in locks:
TypeError: ‘AsyncItemPaged’ object is not iterable .

I have tried different methods like list() and result() but it didn’t work. For the moment, I don’t want to use directly the REST API but the Python SDK.

Does someone has any idea?

Asked By: MoonHorse

||

Answers:

I tried in my environment and got the below results:

In my portal, I created three locks at the resource group level.

Portal:

enter image description here

I want it to list the locks on the resource group level list_at_resource_group_level() method returns that

To list the locks at resource_group_level, you can use the below code:

Code:

from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ManagementLockClient

credential = DefaultAzureCredential()
subscription_id = "subscription id"
resource_group_name = "resourcegrp"

management_lock_client = ManagementLockClient(credential, subscription_id)
locks = management_lock_client.management_locks.list_at_resource_group_level(resource_group_name)

for lock in locks:
    print(lock)

Output:
enter image description here

If you need only the name of the locks you can use print(lock.name) statement.

Output:
enter image description here

If you need to delete the locks at the resource group level you can use the below code.

Code:

from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ManagementLockClient

credential = DefaultAzureCredential()
subscription_id = "0151c365-f598-44d6-b4fd-e2b6e97cb2a7"
resource_group_name = "siliconrg"

management_lock_client = ManagementLockClient(credential, subscription_id)
locks = management_lock_client.management_locks.list_at_resource_group_level(resource_group_name)

for lock in locks:
    management_lock_client.management_locks.delete_at_resource_group_level(resource_group_name, lock.name)
print("The locks are deleted at resource group level")

Output:

enter image description here

Answered By: Venkatesan