概要
Azure SDK for Python を利用して、接続しているテナントのサブスクリプション一覧を取得し、そのサブスクリプション毎にリソースグループの一覧を取得するための Python プログラムです。
実行環境
macOS Big Sur 11.1
python 3.8.3
実行プログラム
GetSubscriptionResourceGroup.py
import time
import argparse
from azure.mgmt.resource import SubscriptionClient, ResourceManagementClient
from azure.identity import AzureCliCredential
# 接続しているテナントのサブスクリプションを操作するオブジェクトを取得
def GetSubscriptionObject():
subscription_client = SubscriptionClient(
credential=AzureCliCredential()
)
return subscription_client
# 特定のサブスクリプションIDのリソースグループを操作するオブジェクトを取得
def GetResourceGroupObject(subs_id):
resource_client = ResourceManagementClient(
credential=AzureCliCredential(),
subscription_id=subs_id
)
return resource_client
# サブスクリプション毎のリソースグループ一覧を取得
def GetSubscriptionResourceGroupList():
# サブスクリプションを操作するオブジェクトの取得
subscription_list = GetSubscriptionObject()
# サブスクリプション毎の処理
for n, subs in enumerate(subscription_list.subscriptions.list()):
print("\n サブスクリプション : {} {}".format(subs.subscription_id, subs.display_name))
# リソースグループ一覧の取得
resource_client = GetResourceGroupObject(subs.subscription_id)
for i, rg in enumerate(resource_client.resource_groups.list()):
print("{} {}".format(rg.name, rg.location))
resource_client.close()
print(" リソースグループ数:{0} \n".format(i+1))
subscription_list.close()
print("サブスクリプション数:{0} \n".format(n+1))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Subscription 一覧の取得')
args = parser.parse_args()
start = time.time()
GetSubscriptionResourceGroupList()
generate_time = time.time() - start
print("\n 取得時間:{0}".format(generate_time) + " [sec] \n")
プログラムの実行
$ python GetSubscriptionResourceGroup.py
サブスクリプション : xxxxxxxx-nnnn-mmmm-ffff-yyyyyyyyyyyy APP-01
rg-test01 japaneast
rg-lab099 japaneast
rg-backup westus2
リソースグループ数:3
:
中略
:
サブスクリプション : zzzzzzzz-pppp-qqqq-rrrr-aaaaaaaaaaaa LAB-01
rg-blob japaneast
rg-DataExplorer japaneast
rg-powerapps japaneast
rg-adlsG2 japaneast
リソースグループ数:4
サブスクリプション数:15
取得時間:9.154601812362671 [sec]
まとめ
Azure CLI で取得するのもよいですが、プログラムでゴリゴリしたいときはこちらですね。