0
1

More than 3 years have passed since last update.

Python で Azure の リソースグループ毎に日単位で使用料金 を取得してみました

Posted at

概要

Azure SDK for Python を利用して、特定のサブスクリプションにあるリソースグループ毎に日単位の降順での使用料金を取得表示するための Python プログラムです。

実行環境

macOS Big Sur 11.1
python 3.8.3

実行プログラム

GetSubscriptionCostManagement_11.py
import os
import time
import argparse
from tabulate import tabulate
import itertools
from itertools import groupby
from azure.identity import AzureCliCredential
from azure.mgmt.costmanagement import CostManagementClient

SUBSCRIPTION_ID = os.environ['ARM_SUBSCRIPTION_ID']

# 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": "Daily",
                "aggregation": {
                    "totalCost": {
                        "name": "PreTaxCost",
                        "function": "Sum"
                    }
                },
                "grouping": [
                    {
                        "type": "Dimension",
                        "name": "ResourceGroup"
                    }
                ]
            }
        }
    )
    return costmanagement


# サブスクリプションIDを指定しリソースグループ毎に CostManagement情報を取得
def GetSubscriptionCsotManagement():

    # 取得コストの キーと値
    row_key = ['UsageCost', 'CostDate', 'ResourceGroup', 'Currency']
    row_value = []

    # CostManagementを操作するオブジェクトの取得
    costmgmt_client = GetCostManagementObject()

    # 指定のサブスクリプションの CostManagement からコストを取得
    print("\nサブスクリプションID : {}\n".format(SUBSCRIPTION_ID))
    costmanagement = GetCostManagement(costmgmt_client, SUBSCRIPTION_ID)

    # 取得したコスト情報を日付で降順ソートし、辞書型に変換する
    row_value = sorted(costmanagement.rows, key=lambda x:x[1], reverse=True)
    row_dict = [dict(zip(row_key,item)) for item in row_value]
    # print(tabulate(row_dict, headers='keys'))

    # リソースフループでソート
    rows = sorted(row_dict, key=lambda x:x['ResourceGroup'], reverse=False)
    # print(tabulate(rows, headers='keys'))

    # リソースグループでグルーピングする
    for key, resgp in groupby(rows, key=lambda x: x['ResourceGroup']):
        # イテレータを複数回使用するための複製
        resgp_list, resgp_cost = itertools.tee(resgp, 2)

        # 日付降順でのコスト表示
        print("\n リソースグループ : ", key)
        print(tabulate(resgp_list, headers='keys'))

        # このリソースグループでのコスト合計の表示
        TotalCost = sum(costList['UsageCost'] for costList in resgp_cost)
        print("\n\t コスト合計:{0}".format(TotalCost) + " JPY")

    costmgmt_client.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")

プログラムの実行

21-09-20 0:56 $ python GetSubscriptionCostManagement_11.py

サブスクリプションID : zzzzzzzz-7777-4444-8448-31783178dddd

 リソースグループ :  rg-netmotion
  UsageCost    CostDate  ResourceGroup    Currency
-----------  ----------  ---------------  ----------
     7.7035    20210919  rg-netmotion     JPY
   397.567     20210918  rg-netmotion     JPY
   447.722     20210917  rg-netmotion     JPY
   809.815     20210916  rg-netmotion     JPY
   791.441     20210915  rg-netmotion     JPY
  1548.48      20210914  rg-netmotion     JPY
    46.221     20210913  rg-netmotion     JPY
   319.183     20210912  rg-netmotion     JPY
    46.221     20210911  rg-netmotion     JPY
   663.029     20210910  rg-netmotion     JPY
    46.221     20210909  rg-netmotion     JPY
   747.32      20210908  rg-netmotion     JPY
    46.221     20210907  rg-netmotion     JPY
    46.221     20210906  rg-netmotion     JPY
    46.221     20210905  rg-netmotion     JPY
   403.659     20210904  rg-netmotion     JPY
   759.404     20210903  rg-netmotion     JPY
   496.18      20210902  rg-netmotion     JPY
    46.221     20210901  rg-netmotion     JPY

     コスト合計:7715.053541357144 JPY

 リソースグループ :  cloud-shell-storage-southeastasia
  UsageCost    CostDate  ResourceGroup                      Currency
-----------  ----------  ---------------------------------  ----------
   0.183482    20210919  cloud-shell-storage-southeastasia  JPY
   1.10085     20210918  cloud-shell-storage-southeastasia  JPY
   1.10085     20210917  cloud-shell-storage-southeastasia  JPY
   1.10085     20210916  cloud-shell-storage-southeastasia  JPY
   1.10088     20210915  cloud-shell-storage-southeastasia  JPY
   1.10088     20210914  cloud-shell-storage-southeastasia  JPY
   1.10084     20210913  cloud-shell-storage-southeastasia  JPY
   1.10073     20210912  cloud-shell-storage-southeastasia  JPY
   1.10075     20210911  cloud-shell-storage-southeastasia  JPY
   1.10082     20210910  cloud-shell-storage-southeastasia  JPY
   1.10073     20210909  cloud-shell-storage-southeastasia  JPY
   1.10073     20210908  cloud-shell-storage-southeastasia  JPY
   1.10073     20210907  cloud-shell-storage-southeastasia  JPY
   1.10073     20210906  cloud-shell-storage-southeastasia  JPY
   1.10081     20210905  cloud-shell-storage-southeastasia  JPY
   1.10085     20210904  cloud-shell-storage-southeastasia  JPY
   1.10088     20210903  cloud-shell-storage-southeastasia  JPY
   1.10085     20210902  cloud-shell-storage-southeastasia  JPY
   1.10088     20210901  cloud-shell-storage-southeastasia  JPY

     コスト合計:19.998122119049988 JPY

 リソースグループ :  rg-hogege
  UsageCost    CostDate  ResourceGroup    Currency
-----------  ----------  ---------------  ----------
    17.3148    20210919  rg-hogege        JPY
    83.1111    20210918  rg-hogege        JPY
    83.1111    20210917  rg-hogege        JPY
    83.1111    20210916  rg-hogege        JPY
    83.1111    20210915  rg-hogege        JPY
    83.1111    20210914  rg-hogege        JPY
    83.1111    20210913  rg-hogege        JPY
    83.1111    20210912  rg-hogege        JPY
    83.1111    20210911  rg-hogege        JPY
    83.1111    20210910  rg-hogege        JPY
    83.1111    20210909  rg-hogege        JPY
    83.1111    20210908  rg-hogege        JPY
    83.1111    20210907  rg-hogege        JPY
    83.1111    20210906  rg-hogege        JPY
    83.1111    20210905  rg-hogege        JPY
    83.1111    20210904  rg-hogege        JPY
    83.1111    20210903  rg-hogege        JPY
    83.1111    20210902  rg-hogege        JPY
    83.1111    20210901  rg-hogege        JPY

     コスト合計:1513.314430817249 JPY

 取得時間:7.457346200942993 [sec] 

まとめ

Azure portal で確認するのもよいですが、プログラムでゴリゴリしたいときはこちらですね。

参考記事

以下の記事を参考にさせていただきました。感謝申し上げます。
pythonで同じiteratorを使い回す方法2選

0
1
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
1