概要
Azure SDK for Python を利用して、接続しているテナントのサブスクリプション毎に使用料金を取得し、一覧表示するための Python プログラムです。
実行環境
macOS Big Sur 11.1
python 3.8.3
実行プログラム
GetSubscriptionCostManagement_3.py
import time
import argparse
from tabulate import tabulate
from azure.identity import AzureCliCredential
from azure.mgmt.resource import SubscriptionClient
from azure.mgmt.costmanagement import CostManagementClient
# 接続しているテナントのサブスクリプションを操作するオブジェクトを取得
def GetSubscriptionObject():
subscription_client = SubscriptionClient(
credential=AzureCliCredential()
)
return subscription_client
# CostManagement情報 を操作するオブジェクトを取得
def GetCostManagementObject():
costmgmt_client = CostManagementClient(
credential=AzureCliCredential()
)
return costmgmt_client
# 指定した Subscription について CostManagement からコストを取得
def GetCostManagement(costmgmt_client, subs_id):
# Query costmanagement
SCOPE = '/subscriptions/{}'.format(subs_id)
costmanagement = costmgmt_client.query.usage(
SCOPE,
{
"type": "Usage",
"timeframe": "MonthToDate",
"dataset": {
"granularity": "None",
"aggregation": {
"totalCost": {
"name": "PreTaxCost",
"function": "Sum"
}
},
"grouping": [
{
"type": "Dimension",
"name": "ResourceGroup"
}
]
}
}
)
return costmanagement
# サブスクリプションIDを指定しリソースグループ毎に CostManagement情報を取得
def GetSubscriptionCsotManagement():
# サブスクリプションを操作するオブジェクトの取得
subscription_list = GetSubscriptionObject()
# CostManagementを操作するオブジェクトの取得
costmgmt_client = GetCostManagementObject()
# 取得コストの キーと値
row_key = ["Subscription", "UsageCost"]
row_value = []
# サブスクリプション毎に CostManagement からコストを取得
for n, subs in enumerate(subscription_list.subscriptions.list()):
# print("\nサブスクリプション : {} {}".format(subs.subscription_id, subs.display_name))
costmanagement = GetCostManagement(costmgmt_client, subs.subscription_id)
# rowsカラムデータを取得し、コストの合計値の取得
TotalCost = sum(cost[0] for cost in costmanagement.rows)
# print("{} \t ¥{}".format(subs.display_name, str(TotalCost)))
# 表示させるコストデータのリスト化
val = [subs.display_name, TotalCost]
row_value.append(val)
# print(row_value)
# 取得したコスト情報を辞書型に変換
row_dict = [dict(zip(row_key,item)) for item in row_value]
# サブスクリプション名で昇順ソートする
rows = sorted(row_dict, key=lambda x:x['Subscription'], reverse=False)
print(tabulate(rows, headers='keys'))
# 全サブスクリプションの合計値を取得
TotalCost = sum(cost[1] for cost in row_value)
print("\n コスト合計:{0}".format(TotalCost) + " JPY \n")
costmgmt_client.close()
subscription_list.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Subscription の コスト取得')
args = parser.parse_args()
start = time.time()
GetSubscriptionCsotManagement()
generate_time = time.time() - start
print("\n 取得時間:{0}".format(generate_time) + " [sec] \n")
プログラムの実行
$ python GetSubscriptionCostManagement_3.py
Subscription UsageCost
----------------------------------- -------------
Microsoft Azure スポンサー プラン01 0 <--- スポンサープランは CostManagement で取得できません
Microsoft Azure スポンサー プラン02 0 <--- スポンサープランは CostManagement で取得できません
Microsoft Azure スポンサー プラン03 0 <--- スポンサープランは CostManagement で取得できません
NSN-01 8236.63
PSP1-01 62695
PSP2-01 28501.1
SAS-01 0.0179941
SSS-01 3058.44
STS1-01 22081.4
STS2-01 8565.18
WTW-01 17428.6
csc-01 6203.38
iapp-01 4192.74
market-ss-01 12301.9
tech-share-01 20262.5
コスト合計:193526.7668466192 JPY
取得時間:100.33618831634521 [sec]
まとめ
Azure portal で確認するのもよいですが、プログラムでゴリゴリしたいときはこちらですね。