Azure-Samples / azure-samples-python-management

This repo contains sample code for management libraries of Azure SDK for Python
MIT License
171 stars 137 forks source link

Looking for an example of using skip_token for pagination #142

Open HappyException opened 1 year ago

HappyException commented 1 year ago

Based on the example here: Quickstart: Your first Python query - Azure Resource Graph | Microsoft Learn Is there an example showing how to properly use the QueryRequestOptions skip_token for pagination?

HappyException commented 1 year ago

Maybe this:

# 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 AzureCliCredential

# Wrap all the work in a function
def getresources( strQuery ):
    # Get your credentials from Azure CLI (development only!) and get your subscription list
    credential = AzureCliCredential()
    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)
    argResultsData = argResults.data

    # If data is paginated the previous query will have a skip_token for itteration
    while argResults.skip_token:
        token = argResults.skip_token
        argQueryOptions.skip_token = argResults.skip_token
        query = arg.models.QueryRequest(subscriptions=subsList, query=strQuery, options=argQueryOptions)
        argResults = argClient.resources(query)
        argResultsData.extend(argResults.data)

    # Display total records returned
    print(f"Total Records:  {argResults.total_records}")
    return(argResultsData)
getresources("Resources | project name, type ")