2
1
お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

【小ネタ】AWS SDKでCost ExplorerのAPIを実行してAWSの使用料を取得する

Last updated at Posted at 2024-06-25

ちょっと再履修

過去の資料を漁っていたのもあるんですが、コストアラートで送られてくるメールを見落としがちなのでAWS SDKでCost ExplorerのAPIを実行してAWSの使用料を取得する方法を復習します。

できたら何かしらのプラットフォームに自動通知していきたい。(LINEとか?)

過去の資料

【とりあえずハンズオン】AWS×LINEで実践!AWS利用料返信Botをつくろう

ソースコード

昔のコード抜粋でなんとなく記載します。

LINE botに使ったコードだと、モジュール化されていないので使いにくい気がするのと
今はAWS以外も触っているので他のクラウドの利用料金がとれるようなモジュールとして作っていきたい気がします。

import os
import boto3
import json
import calendar
from datetime import datetime, date

ce_client = boto3.client('ce')


def main():
    try:
        response = ce_client.get_cost_and_usage(
            TimePeriod={
                'Start': datetime.strftime(start_day, '%Y-%m-%d'),
                'End': datetime.strftime(end_day, '%Y-%m-%d')
            },
            Granularity='MONTHLY',
            Metrics=['UnblendedCost'],
        )
        result_message = response['ResultsByTime'][0]['Total']['UnblendedCost']['Amount']

    except Exception as e:
        # boto3 Client error でも以下の文が表示される
        err_res = e.response['Error']['Message']
        message = '[Error]' + '\n' + 'specify up to the past 12 months.'
        result_message = datetime.strftime(start_day, '%Y-%m-%d') + "-" + datetime.strftime(
            end_day, '%Y-%m-%d') + "\n" + message + "\n" + err_res
    return result_message

IAM

過去の資料から漁ってきたポリシーはちょっと権限が強いので見直したほうが良さそうです。

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "ce:GetCostAndUsage",
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": "logs:CreateLogGroup",
      "Resource": "arn:aws:logs:ap-northeast-1:XXXXXXXXXXXX:*"
    },
    {
      "Effect": "Allow",
      "Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
      "Resource": [
        "arn:aws:logs:ap-northeast-1:XXXXXXXXXXXX:log-group:/aws/lambda/aws_cost_bot:*"
      ]
    }
  ]
}

まとめ

他のクラウドもやっていきつつ、快適に利用料金を見ていきたいのでboto3のCost Explorer APIを復習しました。本格的にマルチクラウド対応の料金確認モジュールを作っていきたいです。

おわり

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