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?

Azureの現在のコストをShellで取得する

Last updated at Posted at 2025-08-11

概要

Azureポータルログインせずに日々のコストを簡単に把握できるようShellを作成しました
閾値を超えると通知する機能はありますが、閾値範囲内でも消し忘れのリソースや急激なリソース利用によるコスト増を知ることができます

作成手順

サービスプリンシパルを作成

ユーザー作成権限のあるアカウントを使って以下のコマンドを実行してサービスプリンシパルを作成します。
出力にappId, displayName, passwordおよびtenantが表示されるのでメモしておきます

## Replace << >> with the appropriate value

az ad sp create-for-rbac \
  --name "<<displayname>>" \
  --role Contributor \
  --scopes /subscriptions/<<subscription id>> \
  --years 2

Shell作成

サービスプリンシパルでログインしてAzureの現在のコストを取得します
参考:

Azure_Cost.sh
## Replace << >> with the appropriate value

#!/bin/bash
az login --service-principal \
  --username <<appId>> \
  --password <<password>> \
  --tenant <<tenant id>> \
  > /dev/null 2>&1

if [ $? -eq 0 ]; then
  echo "ログイン成功"
  sleep 2
  azurecost=$( \
  az rest --method post \
    --uri "https://management.azure.com/subscriptions/<<subscription id>>/providers/Microsoft.CostManagement/query?api-version=2025-03-01" \
    --body '{
      "type": "ActualCost",
      "timeframe": "MonthToDate",
      "dataset": {
        "granularity": "None",
        "aggregation": {
          "totalCost": {
            "name": "PreTaxCost",
            "function": "Sum"
          }
        }
      }
    }' \
    --query "properties.rows[0][0]"
  )

  azurecost_int=$(echo "$azurecost" | awk '{print int($1)}')

  if [ "$azurecost_int" -ge 1 ]; then
    snsmessage="Azureの現在のコストは $azurecost_int 円です"
  else
    snsmessage="Azureコスト取得でエラー発生しました"
  fi

  echo $snsmessage

else
  echo "ログイン失敗"
  exit 1
fi

実行

Shellを実行してして現在のコストが取得できることを確認します
"Too many requests. Please retry."は時々発生するためピーク時間を避けるかリトライの仕組みの追加が必要です

# ログイン失敗
$ /bin/bash Azure_Cost.sh
ログイン失敗

# エラーで取得失敗
$ /bin/bash Azure_Cost.sh
ログイン成功
ERROR: Too Many Requests({"error":{"code":"429","message":"Too many requests. Please retry."}})
Azureコスト取得でエラー発生しました
[opc@syd-vm-08-linux-rundeck scripts]$

# 取得成功
$ /bin/bash Azure_Cost3.sh
ログイン成功
Azureの現在のコストは 864 円です

Azure Portalと一致しています
image.png

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?