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 の リソースグループ単位で使用料金 を取得してみました

Posted at

概要

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

実行環境

macOS Big Sur 11.1
python 3.8.3

実行プログラム

GetSubscriptionCostManagement_1.py

import os
import time
import argparse
from tabulate import tabulate
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": "None",
                "aggregation": {
                    "totalCost": {
                        "name": "PreTaxCost",
                        "function": "Sum"
                    }
                },
                "grouping": [
                    {
                        "type": "Dimension",
                        "name": "ResourceGroup"
                    }
                ]
            }
        }
    )
    return costmanagement


# サブスクリプションIDを指定しリソースグループ毎に CostManagement情報を取得
def GetSubscriptionCsotManagement():
    
    # CostManagementを操作するオブジェクトの取得
    costmgmt_client = GetCostManagementObject()

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

プログラムの実行

$ python GetSubscriptionCostManagement_1.py

サブスクリプションID : xxxxxxxx-1111-4444-9779-66546544cccc

  UsageCost  ResourceGroup                                     Currency
-----------  ------------------------------------------------  ----------
 11887       mc_rg_ituru_aks_cni_ituruakscnicluster_japaneast  JPY
  4337.11    rg-nhegheg-dev-001                                JPY
  3137.39    rg-tttt-mig                                       JPY
  1580.04    rg-yaya-02                                        JPY
     :
    中略
     :
    20.4664  rg_c4th                                           JPY
    13.6087  rg_ext1                                           JPY
     0       aksonhci                                          JPY
     0       rg-sh-dup-01                                      JPY
     0       rg-yaya-03                                        JPY

	 コスト合計:28501.055925536668 JPY

 取得時間:6.922018051147461 [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?