Prerequisites
- LINE Notify must be configured (https://notify-bot.line.me/ )
- CloudWatch permissions must be granted and AWS CLI must be executable
Code
Mostly reusing a script built for another purpose…
import os,sys,datetime
import boto3
import requests
import datetime
def main():
get_aws_cost()
send_line_notify(LINE_TEXT)
def send_line_notify(notification_message):
line_notify_token = 'xxxxxxxxxxxxxxxxxxxxxxx'
line_notify_api = 'https://notify-api.line.me/api/notify'
headers = {'Authorization': f'Bearer {line_notify_token}'}
data = {'message': f'message: {notification_message}'}
requests.post(line_notify_api, headers = headers, data = data)
def get_aws_cost():
AWS_REGION = "us-east-1"
response = boto3.client('cloudwatch', region_name='us-east-1')
today_date = datetime.date.today().strftime('%Y/%m/%d')
def get_value():
get_demesion = [{'Name': 'Currency', 'Value': 'USD'}]
data = response.get_metric_statistics(
Namespace='AWS/Billing',
MetricName='EstimatedCharges',
Period=86400,
StartTime=today_date + " 00:00:00",
EndTime=today_date + " 23:59:59",
Statistics=['Maximum'],
Dimensions=get_demesion
)
for info in data['Datapoints']:
return info['Maximum']
total_value = get_value()
global LINE_TEXT
LINE_TEXT='AWS usage charges to date are $' + str(total_value)
if __name__ == "__main__":
main()