forked from guessi/aws-cost-explorer-report
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aws-cost-explorer-report.py
executable file
·103 lines (80 loc) · 2.63 KB
/
aws-cost-explorer-report.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
#!/usr/bin/env python3
import boto3
import click
from calendar import monthrange
from datetime import datetime
from prettytable import PrettyTable
# define table layout
pt = PrettyTable()
pt.field_names = [
'TimePeriodStart',
'LinkedAccount',
'Service',
'Amount',
]
pt.align = "l"
pt.align["Amount"] = "r"
def get_cost_and_usage(bclient: object, start: str, end: str) -> list:
cu = []
while True:
data = bclient.get_cost_and_usage(
TimePeriod={
'Start': start,
'End': end,
},
Granularity='MONTHLY',
Metrics=[
'UnblendedCost',
],
GroupBy=[
{
'Type': 'DIMENSION',
'Key': 'LINKED_ACCOUNT',
},
{
'Type': 'DIMENSION',
'Key': 'SERVICE',
}
],
)
cu += data['ResultsByTime']
token = data.get('NextPageToken')
if not token:
break
return cu
def fill_table_content(results: list, start: str, end: str) -> None:
total = 0
for result_by_time in results:
for group in result_by_time['Groups']:
amount = float(group['Metrics']['UnblendedCost']['Amount'])
total += amount
# Skip, if total amount less then 0.00001 USD
if amount < 0.00001:
continue
pt.add_row([
result_by_time['TimePeriod']['Start'],
group['Keys'][0],
group['Keys'][1],
format(amount, '0.5f'),
])
print("Total: {:5f}".format(total))
@click.command()
@click.option('-P', '--profile', help='profile name')
@click.option('-S', '--start', help='start date (default: 1st date of current month)')
@click.option('-E', '--end', help='end date (default: last date of current month)')
def report(profile: str, start: str, end: str) -> None:
# set start/end to current month if not specify
if not start or not end:
# get last day of month by `monthrange()`
# ref: https://stackoverflow.com/a/43663
ldom = monthrange(datetime.today().year, datetime.today().month)[1]
start = datetime.today().replace(day=1).strftime('%Y-%m-%d')
end = datetime.today().replace(day=ldom).strftime('%Y-%m-%d')
# cost explorer
SERVICE_NAME = 'ce'
bclient = boto3.Session(profile_name=profile).client(SERVICE_NAME)
results = get_cost_and_usage(bclient, start, end)
fill_table_content(results, start, end)
print(pt)
if __name__ == '__main__':
report()