+-
【Azure Developer】Python 获取 Azure 中订阅(subscription)信息,包含ID, Name等

问题描述

在Azure AD中注册一个Applicaiton后,对其进行授权,能够查看所有订阅的ReadOnly权限,然后,是否可以同通过Python代码,在完成Authorization后(使用Client ID, Client Secret),List能查看到所有的订阅信息(包含ID和名称等)?

 

问题答案

可以的。

在Azure SDK for Python中,有 SubscriptionsOperations 类,可以 List 出所有的Subscription对象。 

SubscriptionsOperations Class,You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. 

List : Gets all subscriptions for a tenant. (https://docs.microsoft.com/en-us/python/api/azure-mgmt-subscription/azure.mgmt.subscription.operations.subscriptionsoperations?view=azure-python#list---kwargs-)

 

示例代码(把其中AAD认证相关信息替换即可)

from azure.identity import ClientSecretCredential
from azure.mgmt.resource import SubscriptionClient
from msrestazure.azure_cloud import AZURE_CHINA_CLOUD

credentials = ClientSecretCredential(client_id='', client_secret='', tenant_id='',authority=AZURE_CHINA_CLOUD.endpoints.active_directory)

subscription_client = SubscriptionClient(credentials, base_url=AZURE_CHINA_CLOUD.endpoints.resource_manager, credential_scopes=["https://management.chinacloudapi.cn/.default"])

subscription_list=subscription_client.subscriptions.list()

for subscription in list(subscription_list):
print(f"{subscription.subscription_id}   {subscription.display_name}")

 

参考资料

SubscriptionsOperations Class : https://docs.microsoft.com/en-us/python/api/azure-mgmt-subscription/azure.mgmt.subscription.operations.subscriptionsoperations?view=azure-python