-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
64 lines (52 loc) · 1.62 KB
/
lambda_function.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
# encoding: utf-8
import json
import datetime
import requests
import boto3
import os
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Configuration of Slack
SLACK_POST_URL = os.environ['slackPostURL']
SLACK_CHANNEL = os.environ['slackChannel']
response = boto3.client('cloudwatch', region_name='us-east-1')
get_metric_statistics = response.get_metric_statistics(
Namespace='AWS/Billing',
MetricName='EstimatedCharges',
Dimensions=[
{
'Name': 'Currency',
'Value': 'USD'
}
],
StartTime=datetime.datetime.today() - datetime.timedelta(days=1),
EndTime=datetime.datetime.today(),
Period=86400,
Statistics=['Maximum'])
cost = get_metric_statistics['Datapoints'][0]['Maximum']
date = get_metric_statistics['Datapoints'][0]['Timestamp'].strftime('%Y/%m/%d')
def build_message(cost):
if float(cost) >= 10.0:
color = "#ff0000" #red
elif float(cost) > 0.0:
color = "warning" #yellow
else:
color = "good" #green
text = "The billed amount of AWS up to %s is $%s" % (date, cost)
atachements = {"text":text,"color":color}
return atachements
def lambda_handler(event, context):
content = build_message(cost)
# Slack setting
slack_message = {
'channel': SLACK_CHANNEL,
"attachments": [content],
}
# POST
try:
req = requests.post(SLACK_POST_URL, data=json.dumps(slack_message))
logger.info("Message posted to %s", slack_message['channel'])
except requests.exceptions.RequestException as e:
logger.error("Request failed: %s", e)