1
votes

Just wondering if there is a simple way to get the resource group name from an Azure resource object i.e. Disk, Snapshot object

Currently I use the resource URI and derive the resource group from that:

# ID example: '/subscriptions/123/resourceGroups/MyRG/providers/Microsoft.Compute/disks/disk-a
resource_group = [value for value in str(disk.id).split("/") if value][3]

Output

>> MyRG

I can't seem to see a way to do something like:

disk.resource_group
2

2 Answers

1
votes

Looking at the MSDN, I don't believe there is a resource_group property.

What I usually do is create a method(similar to what you have done) to fetch the resource group from a resource ID:

def get_resource_group_from_id(resource_id):
    return resource_id.lstrip("/").split("/")[3]

Then I just use this method everywhere I need to get the resource group:

from azure.mgmt.compute import ComputeManagementClient
from azure.common.client_factory import get_client_from_cli_profile

compute_client = get_client_from_cli_profile(ComputeManagementClient)

for disk in compute_client.disks.list():
    resource_group = get_resource_group_from_id(resource_id=disk.id)

However, I'm not a fan of this since I'm used to just fetching this directly from the resource.

You could raise a Feature Request with azure-sdk-for-python to get this property included in the objects. Azure PowerShell and Azure CLI include this property, so I don't see why Azure Python SDK shouldn't include it.

Another option could be to include a resource_group tag, then you can fetch it directly from the resource.

0
votes

Below is the Azure SDK for python:

https://docs.microsoft.com/en-us/python/api/overview/azure/?view=azure-python

I think your needs need to be specific to a specific service, And in general, a large range can be specific to a small range, but the specific objects of each service do not seem to define a method to obtain the corresponding resource group. I think your idea may not be realized.