LoginSignup
1
2

More than 1 year has passed since last update.

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

Posted at

概要

Azure SDK for Python を利用して、接続しているテナントのサブスクリプション毎に、そのサブスクリプションにあるリソースグループ単位での使用料金を取得し、使用料金の高い順にソート表示するための Python プログラムです。

実行環境

macOS Big Sur 11.1
python 3.8.3

実行プログラム

GetSubscriptionCostManagement_2.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()

    # サブスクリプション毎に CostManagement からコストを取得
    for n, subs in enumerate(subscription_list.subscriptions.list()):
        # print("\nサブスクリプション : {}  {}\n".format(subs.subscription_id, subs.display_name))
        print("\nサブスクリプション : {}\n".format(subs.display_name))
        costmanagement = GetCostManagement(costmgmt_client, subs.subscription_id)

        # rowsカラムデータを取得し、コストで降順ソートする
        rows = sorted(costmanagement.rows, key=lambda x:x[0], reverse=True)
        header = ['UsageCost', 'ResourceGroup', 'Currency']
        print(tabulate(rows, headers=header))

        # コストの合計値の取得
        TotalCost = sum(cost[0] for cost in rows)
        print("\n\t コスト合計:{0}".format(TotalCost) + " JPY \n")

    print("\n サブスクリプション数:{0} \n".format(n+1))
    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_2.py

サブスクリプション : iapp-01

  UsageCost  ResourceGroup                             Currency
-----------  ----------------------------------------  ----------
4191.64      networldappazure                          JPY
   0.749086  networldappazure-japaneastwebspace-linux  JPY
   0.357419  testrg                                    JPY
   0         yaya-cv-0803                              JPY

     コスト合計:4192.743525909148 JPY 

       :
    かなり中略
       :

サブスクリプション : NNN-01

  UsageCost  ResourceGroup                      Currency
-----------  ---------------------------------  ----------
  6871.69    rg-netmotion                       JPY
  1347.09    rg-jimjim                          JPY
    17.8423  cloud-shell-storage-southeastasia  JPY

     コスト合計:8236.625178712422 JPY 


 サブスクリプション数:15 

 取得時間:100.4397029876709 [sec] 

まとめ

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

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