😀

Azure Cost Management の Query を使って「実際のコスト」を Azure CLI で取得してみ

に公開

私の周辺では、翌月になってはじめて先月のコストが増えている事に気づく、という事例がちらほらあります。私の対策方法は、今まで使ったことのない Azure リソースを作成した時などは特に、当日から数週間はコストの増加を毎日確認しています。今時はコストのアラートを設定できるので、設定値を超えると自動でメールを送ることも可能になりました。もう一つの対策として、毎朝「実際のコスト」がメールや Teams チャネルに送信され、日課として毎朝コストを見る習慣をつけておくのがよいのではないかと思います。そこで今回は、Azure Cost Management の Query を使って「実際のコスト」を Azure CLI で取得してみました。

当月のコストを取得する例

timeframeMonthToDate で実行します。

bash
subscription_id=$(az account show --query id --output tsv)

az rest \
  --method post \
  --url "https://management.azure.com/subscriptions/$subscription_id/providers/Microsoft.CostManagement/query?api-version=2023-03-01" \
  --body '{
      "type": "Usage",
      "timeframe": "MonthToDate",
      "dataset": {
        "granularity": "None",
        "aggregation": {
          "totalCost": {
            "name": "PreTaxCost",
            "function": "Sum"
          }
        }
      }
    }' \
  --query "properties.rows[0]"

[
  227.01741212341477,
  "JPY"
]

当月のコスト

azure-cost-02.png

先月のコストを取得する例

timeframeTheLastMonth で実行すると下記のエラーとなるため、Custom にして timePeriod を追加します。

Bad Request({"error":{"code":"BadRequest","message":"Invalid query definition, timeframe TheLastMonth is currently not supported. (Request ID: 4efcbdea-9ffc-4255-b3c4-c2e6549af505)"}})

bash
subscription_id=$(az account show --query id --output tsv)

az rest \
  --method post \
  --url "https://management.azure.com/subscriptions/$subscription_id/providers/Microsoft.CostManagement/query?api-version=2023-03-01" \
  --body '{
      "type": "Usage",
      "timeframe": "Custom",
      "dataset": {
        "granularity": "None",
        "aggregation": {
          "totalCost": {
            "name": "PreTaxCost",
            "function": "Sum"
          }
        }
      },
      "timePeriod": {
        "from": "2023-08-01",
        "to": "2023-08-31"
      }
    }' \
  --query "properties.rows[0]"

[
  7998.907108950386,
  "JPY"
]

先月のコスト

azure-cost-01.png

補足情報

月初だからなのか、下記のように頻繁にリターンコード 429 になりました。バッチ処理などで月初に実行される事を考えると、リトライ処理を組み込んだ方が安心みたいです。

Too Many Requests({"error":{"code":"429","message":"Too many requests. Please retry."}})

参考

https://learn.microsoft.com/ja-jp/rest/api/cost-management/query/usage

Discussion