12
9

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 5 years have passed since last update.

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

Posted at

なぜ書いたか

  • 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分で書いたク○コードだが、運用するわけではないし、良いのだこれくらいで(と自分に言い聞かせる)
12
9
2

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
12
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?