각 서비스에 대한 AWS 요금 청구 및 Slack(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()
결실
감상
Reference
이 문제에 관하여(각 서비스에 대한 AWS 요금 청구 및 Slack(Python) 알림), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/ikedaosushi/items/9d2147d18b6e1651228f텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)