简体   繁体   中英

Python SDK Azure Resource Graph response not iterable

I'm trying to query resources in Azure subscriptions using the Azure Resource Graph python SDK from within an Azure Function. The fact it's using the Functions runtime isn't important, the code also doesn't work locally. The query itself works very well. However, I then want to use the results in a subsequent step, and that's where I'm hitting an issue.

    credentials, *_ = get_azure_cli_credentials()

    subscription_client = SubscriptionClient(credentials)
    subs = [sub.as_dict() for sub in subscription_client.subscriptions.list()]
    subs_list = []
    for sub in subs:
        subs_list.append(sub.get('subscription_id'))

    client = rg.ResourceGraphClient(credentials)

    request = QueryRequest(subscriptions=subs_list, query="resources | where type == 'microsoft.storage/storageaccounts'| where properties.supportsHttpsTrafficOnly == 'false'")

    response = client.resources(request)
    logging.info(response)

I tried the following:

for resource in response:
    logging.info(resource)

This fails with Exception: TypeError: 'QueryResponse' object is not iterable . For reference: https://docs.microsoft.com/en-us/python/api/azure-mgmt-resourcegraph/azure.mgmt.resourcegraph.models.queryresponse?view=azure-python

logging.info(response['data'])

This fails with Exception: TypeError: 'QueryResponse' object is not subscriptable . Anybody know how to use this response now? Thanks!

The result type QueryResponse has a property data that you can use to access the resulting data. Since QueryResponse isn't a dictionary but rather a class, you can't access the data property with subscripting (square brackets). Instead you need to access it as property of the class like response.data .

The data property is a dict with two keys, columns which is a list of all the columns returned and the type of data each column contains, and rows which is a list of all of the rows in the result matching the query.

So your loop will probably look something like:

for resource in response.data['rows']:
    logging.info(resource)

Response format can be simplified to match resource JSON by passing QueryRequestOptions :

client = ResourceGraphClient(credentials)

options = QueryRequestOptions(
    result_format=ResultFormat.object_array
)

request = QueryRequest(subscriptions=subs_list, query="<query>", options=options)

response = client.resources(request)

for resource in response.data:
    logging.info(resource)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM