Python
AWS

AWSの料金をサービス毎に取得してSlackに通知する(Python)

なぜ書いたか

  • AWSの料金通知についてたくさんの方が記事を書かれている
  • が、サービスごとに料金を取得するPythonスクリプトはいい感じにコピペできるものがなかった
  • そんなに頑張るようなコードでもないので完全にコピペ用に残す

環境

$ python -V
Python 3.6.5 # >=3.4 であれば動くはず
$ pip install requests boto3

コード

import os, json
from datetime import datetime, timedelta

import requests, boto3

SLACK_ENDPOINT = "your-incoming-webhook-url"
# Please add services you want to know metrics.
SERVICES = ["AmazonEC2", "AmazonRoute53", "AmazonS3", "AWSLambda", "All"]

def notify_invoice():
    # Prepare to get metrics
    client = boto3.client("cloudwatch", region_name="us-east-1")

    seconds_in_1day = 86400
    fields = []
    today = datetime.today()
    yesterday = today - timedelta(days=1)

    for service in SERVICES:
        # Setup dimensions
        dimensions = [{"Name": "Currency", "Value": "USD"}] 
        if service != "All":
            dimensions.append({"Name": "ServiceName", "Value": service})

        # Get metrics
        res = client.get_metric_statistics(
            Namespace="AWS/Billing",
            MetricName="EstimatedCharges",
            Dimensions=dimensions,
            StartTime=yesterday,
            EndTime=today,
            Period=seconds_in_1day,
            Statistics=["Average"]
        )

        # Continue if response wouldn't have data
        if len(res["Datapoints"]) == 0:
            continue

        # Append result to fields list
        invoice = res["Datapoints"][0].get("Average", "")
        field = {"title": service, "value": "{} USD".format(invoice)}
        fields.append(field)

    # Prepare to send the message 
    payload = {
        "text": "Your invoice untill yesterday",
        "username": "Invoice Notificater",
        "icon_emoji": ":moneybag:",
        "attachments": [{"fields": fields}]
    }

    # Send message
    requests.post(SLACK_ENDPOINT, data=json.dumps(payload))


if __name__ == "__main__":
    notify_invoice()

結果

Slack_-_Osushi.png

所感

  • 誰がどう見ても30分で書いたク○コードだが、運用するわけではないし、良いのだこれくらいで(と自分に言い聞かせる)