0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

# Python で Azure の サブスクリプション単位で使用料金 を取得してみました

Last updated at Posted at 2021-09-19

概要

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 で確認するのもよいですが、プログラムでゴリゴリしたいときはこちらですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?