user2156115
user2156115

Reputation: 1247

How to get all resources with details from Azure subscription via Python

I am trying to get all resources and providers from Azure subscription by using Python SDK. Here is my code:

  1. get all resources by "resource group"
  2. extract id of each resource within "resource group"
  3. then calling details about particular resource by its id

The problem is that each call from point 3. requires a correct "API version" and it differs from object to object. So obviously my code keeps failing when trying to find some common API version that fits to everything.

Is there a way to retrieve suitable API version per resource in resource group ??? (similarly as retrieving id, name, ...)

# Import specific methods and models from other libraries
from azure.mgmt.resource import SubscriptionClient
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient

credential = AzureCliCredential()
client = ResourceManagementClient(credential, "<subscription_id>")
rg = [i for i in client.resource_groups.list()]

# Retrieve the list of resources in "myResourceGroup" (change to any name desired).
# The expand argument includes additional properties in the output.

rg_resources = {}

for i in range(0, len(rg)):
    rg_resources[rg[i].as_dict()
                 ["name"]] = client.resources.list_by_resource_group(
                     rg[i].as_dict()["name"],
                     expand="properties,created_time,changed_time")

data = {}

for i in rg_resources.keys():
    details = []
    for _data in iter(rg_resources[i]):
        a = _data
        details.append(client.resources.get_by_id(vars(_data)['id'], 'latest'))
    data[i] = details

print(data)

error:

azure.core.exceptions.HttpResponseError: (NoRegisteredProviderFound) No registered resource provider found for location 'westeurope' and API version 'latest' for type 'workspaces'. The supported api-versions are '2015-03-20, 2015-11-01-preview, 2017-01-01-preview, 2017-03-03-preview, 2017-03-15-preview, 2017-04-26-preview, 2020-03-01-preview, 2020-08-01, 2020-10-01, 2021-06-01, 2021-03-01-privatepreview'. The supported locations are 'eastus, westeurope, southeastasia, australiasoutheast, westcentralus, japaneast, uksouth, centralindia, canadacentral, westus2, australiacentral, australiaeast, francecentral, koreacentral, northeurope, centralus, eastasia, eastus2, southcentralus, northcentralus, westus, ukwest, southafricanorth, brazilsouth, switzerlandnorth, switzerlandwest, germanywestcentral, australiacentral2, uaecentral, uaenorth, japanwest, brazilsoutheast, norwayeast, norwaywest, francesouth, southindia, jioindiawest, canadaeast, westus3

Upvotes: 1

Views: 3324

Answers (1)

burna
burna

Reputation: 2962

What information exactly do you want to retrieve from the resources?

In most cases, I would recommend to use the Graph API to query over all resources. This is very powerful, as you can query the whole platform using a simple Query language - Kusto Query Lanaguage (KQL)

You can try the queries directly in the Azure service Azure Resource Graph Explorer in the Portal

A query that summarizes all types of resources would be:

resources 
| project resourceGroup, type
| summarize count() by type, resourceGroup 
| order by count_

A simple python-codeblock can be seen on the linked documentation above. The below sample uses DefaultAzureCredential for authentication and lists the first resource in detail, that is in a resource group, where its name starts with "rg".

# Import Azure Resource Graph library
import azure.mgmt.resourcegraph as arg
# Import specific methods and models from other libraries
from azure.mgmt.resource import SubscriptionClient
from azure.identity import DefaultAzureCredential

# Wrap all the work in a function
def getresources( strQuery ):
    # Get your credentials from environment (CLI, MSI,..)
    credential = DefaultAzureCredential()
    subsClient = SubscriptionClient(credential)
    subsRaw = []
    for sub in subsClient.subscriptions.list():
        subsRaw.append(sub.as_dict())
    subsList = []
    for sub in subsRaw:
        subsList.append(sub.get('subscription_id'))

    # Create Azure Resource Graph client and set options
    argClient = arg.ResourceGraphClient(credential)
    argQueryOptions = arg.models.QueryRequestOptions(result_format="objectArray")

    # Create query
    argQuery = arg.models.QueryRequest(subscriptions=subsList, query=strQuery, options=argQueryOptions)

    # Run query
    argResults = argClient.resources(argQuery)

    # Show Python object
    print(argResults)

getresources("Resources | where resourceGroup startswith 'rg' | limit 1")

Upvotes: 2

Related Questions