This repository has been archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AWSBillongPost.py
executable file
·124 lines (100 loc) · 4.28 KB
/
AWSBillongPost.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys,json,datetime
import ConfigParser
import boto3
import slackweb
iniFile = ConfigParser.SafeConfigParser()
iniFile.read(os.path.abspath(os.path.dirname(__file__)) + '/.auth_info')
# ==== AWS認証情報 ====
region = "us-east-1"
keyID = iniFile.get('aws', 'AWS_KEY_ID')
secretKeyID = iniFile.get('aws', 'AWS_SECRET_KEY')
# ==== Slack認証設定 ====
slackWebhook = iniFile.get('slack', 'WEBHOOK_URL')
slackChannel = iniFile.get('slack', 'CHANNEL')
slackUser = iniFile.get('slack', 'USER')
# ==== AWS認証処理 ====
awsSession = boto3.Session(
aws_access_key_id = keyID,
aws_secret_access_key = secretKeyID,
region_name = region
)
cloudwatchConn = awsSession.client('cloudwatch')
# ==== 昨日/一昨日の日付を取得する ====
lastDay = datetime.date.today() -datetime.timedelta(1)
lastDayStr = lastDay.strftime('%Y/%m/%d')
befLastDayStr = (datetime.date.today() -datetime.timedelta(2)).strftime('%Y/%m/%d')
# ==== リストの宣言 ====
serviceNameList = []
serviceValueList = []
befServiceValueList = []
# ==== 関数getValue(サービス名,日付) ====
# ※ getValue(サービス名,日付)で、指定された日付までの利用料金を返す
# サービス名が「ALL」の場合は全体の金額を取得する
def getValue(sName,checkDay):
if sName == 'ALL':
getDemesion = [{'Name': 'Currency', 'Value': 'USD'}]
else:
getDemesion = [{'Name': 'ServiceName', 'Value': sName },{'Name': 'Currency', 'Value': 'USD'}]
data = cloudwatchConn.get_metric_statistics(
Namespace = 'AWS/Billing',
MetricName = 'EstimatedCharges',
Period = 86400,
StartTime = checkDay + " 00:00:00",
EndTime = checkDay + " 23:59:59",
Statistics = ['Maximum'],
Dimensions = getDemesion
)
for info in data['Datapoints']:
return info['Maximum']
# ==== 関数getListServiceValue(サービスリスト,日付) ====
# ※ getListServiceValue(サービスリスト,日付)で、指定された日付までの利用料金を返す
# 返り値はリスト。
def getListServiceValue(checkServiceList,checkDay):
returnValueList = []
for sName in checkServiceList:
sValue = getValue(sName,checkDay)
if sValue is None:
sValue =0
returnValueList.append(sValue)
return returnValueList
# ==== AWSのメトリックのサービスリストを取得する ====
# もうちょっと良い書き方が無いものか…
jsonValue = cloudwatchConn.list_metrics()
for attr1 in jsonValue.get('Metrics'):
for attr2 in attr1.get('Dimensions'):
if attr2.get('Name') == "ServiceName":
serviceNameList.append(attr2.get('Value'))
serviceNameList.sort()
# ==== サービス別の金額を取得する ====
serviceValueList = getListServiceValue(serviceNameList,lastDayStr)
befServiceValueList = getListServiceValue(serviceNameList,befLastDayStr)
# ==== トータルの金額を取得する ====
lastDayTotalValue = getValue('ALL',lastDayStr)
befLastDayTotalValue = getValue('ALL',befLastDayStr)
if lastDay.day == 1:
ratioTotal = lastDayTotalValue
else:
ratioTotal = lastDayTotalValue - befLastDayTotalValue
# ==== SlackへPostするデータの作成 ====
slactText = '昨日までのAWSの利用料金は *$' + str(lastDayTotalValue) + '* (前日比 + *$' + str(ratioTotal) + '* )' + 'になります'
slack = slackweb.Slack(url=slackWebhook)
attachments = []
attachment = {'pretext': '各サービス別の利用料金','fields': []}
for var in range(0, len(serviceNameList)):
if lastDay.day == 1:
serviceRatio = serviceValueList[var]
else:
serviceRatio = serviceValueList[var] - befServiceValueList[var]
item={'title': serviceNameList[var] ,
'value': ' $' + str(serviceValueList[var]) + ' (前日比 +$' + str(serviceRatio) + ') ' ,
'short': "true"}
attachment['fields'].append(item)
attachments.append(attachment)
slack.notify( text = slactText,
channel = slackChannel,
username = slackUser,
icon_emoji = ":aws-icon:",
attachments=attachments
)