Skip to content

Commit 7138903

Browse files
committed
Add first cut at fetching EC2 server statistics
With this merged, Zulip bots will include the server count in the notification. The calculation is: Servers = (Number of EC2 servers) - (Terminated) This is useful to prevent the mistake of leaving servers running after done using them. Signed-off-by: Fujimoto Seiji <[email protected]>
1 parent ebd7506 commit 7138903

File tree

3 files changed

+18
-4
lines changed

3 files changed

+18
-4
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ zulip:
7575

7676
### How to fix "Permission denied" error on AWS
7777

78-
You need `AWSBudgetsReadOnlyAccess` to fetch the AWS usage data.
78+
You need `AWSBudgetsReadOnlyAccess` and ` AmazonEC2ReadOnlyAccess` to fetch the AWS usage data.
7979

8080
Check your current permission policy on IAM > Users.
8181

config.yaml.tmpl

+1
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@ zulip:
1212
{year}年{month}月の月額コストをお知らせします。
1313
* 本日{day}日までの利用分は ${cost:.2f} です。
1414
* AWSの予測によると、今月の合計費用は ${forecast:.2f} です。
15+
* 現在、EC2で起動しているサーバーは{nserver}台です。

report.py

+16-3
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,18 @@ def get_monthly_cost(config, aws_profile_name):
2323
forecast = resp['Budgets'][0]['CalculatedSpend']['ForecastedSpend']['Amount']
2424
return (float(cost), float(forecast))
2525

26+
def get_server_stats(config, aws_profile_name):
27+
# TODO Define AWSUsage() class to factor out the boilarplate.
28+
session = boto3.Session(profile_name=aws_profile_name)
29+
client = session.client("ec2")
30+
resp = client.describe_instances()
31+
nserver = 0
32+
for resv in resp["Reservations"]:
33+
for inst in resv['Instances']:
34+
if inst['State']['Name'] != 'terminated':
35+
nserver += 1
36+
return nserver
37+
2638
def send_message(config, message):
2739
client = zulip.Client(site=config['zulip']['site'],
2840
email=config['zulip']['email'],
@@ -35,16 +47,17 @@ def send_message(config, message):
3547
'content': message
3648
})
3749

38-
def format_message(config, cost, forecast):
50+
def format_message(config, cost, forecast, nserver):
3951
today = datetime.date.today()
4052
template = config['zulip']['message']
4153
return template.format(year=today.year, month=today.month, day=today.day,
42-
cost=cost, forecast=forecast)
54+
cost=cost, forecast=forecast, nserver=nserver)
4355

4456
def main(aws_profile_name = "default", dryrun=False):
4557
config = load_config()
4658
cost, forecast = get_monthly_cost(config, aws_profile_name)
47-
message = format_message(config, cost, forecast)
59+
nserver = get_server_stats(config, aws_profile_name)
60+
message = format_message(config, cost, forecast, nserver)
4861
if dryrun:
4962
print(message)
5063
else:

0 commit comments

Comments
 (0)