-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathec2notify.py
More file actions
118 lines (101 loc) · 3.92 KB
/
ec2notify.py
File metadata and controls
118 lines (101 loc) · 3.92 KB
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
import smtplib
import traceback
from ConfigParser import ConfigParser
from goodreads_quotes import Goodreads
import boto3
import ast
__author__ = 'naren'
ec2 = boto3.resource('ec2')
config = ConfigParser()
config.read('ec2notify_personal.cfg')
SUBJECT_TMPL = "ec2notify --> {0} TEAM"
BODY_TMPL = """This is an autogenerated email from ec2notify for the team : {0}.
Please shutdown the unused instances !!!\n
The following are the running ec2 instances :
format : Name, Instance-id, Instance-type.\n
"""
def send_email(sender, pwd, recipient, subject, body):
"""Send an email to a user or list of users
:param sender: A string which is the email of sender
:param pwd: A string which is the pass phrase of the sender email
:param recipient: A string or list of strings which is the recipient(s) email id(s)
:param subject: A string which is the subject for email
:param body: A string or docstring which is the body of the email
"""
gmail_user = sender
gmail_pwd = pwd
from_ = sender
to = recipient if type(recipient) is list else [recipient]
subject = subject
text = body
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (from_, ", ".join(to), subject, text)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(from_, to, message)
server.close()
print 'successfully sent the mail'
except:
print traceback.format_exc()
print "failed to send mail"
def filter_by_tag(key, value):
"""Filter the running instances by given tag(team)
:param key: A string which is the key for the tag
:param value: A string which is the value of the tag, here its team name
:return: A list of tuples which is the information of the running instances
example : [(name, instance_id, instance_type), (name, instance_id, instance_type) ...]
"""
results = []
fltr = [{'Name': 'tag:' + key, 'Values': value}, {'Name': 'instance-state-name', 'Values': ['running']}]
instances = ec2.instances.filter(
Filters=fltr)
for instance in instances:
tags = instance.tags
instance_name = None
for tag in tags:
if tag['Key'] == 'Name':
instance_name = tag['Value']
result = (instance_name, instance.id, instance.instance_type)
results.append(result)
return results
def draft_email(team, instance_info):
"""Draft the email for the team members
:param team: A string which is the team name
:param instance_info: A list of tuples which is the information of the running instances
example : [(name, instance_id, instance_type), (name, instance_id, instance_type) ...]
:return: Subject and body for email as two separate strings
"""
qotd = Goodreads.get_daily_quote()
subject = SUBJECT_TMPL.format(team.upper())
body = BODY_TMPL.format(team)
for detail in instance_info:
body = body + str(detail) + '\n'
body += "\n\nQOTD : {0} \n - {1} \n".format(qotd['quote'], qotd['author'])
return subject, body
def run():
"""Start point of the code
All other functions are meaningfully called here
"""
tags = config.get('email', 'tags')
tags = ast.literal_eval(tags)
recipients = config.get('email', 'recipients')
recipients = ast.literal_eval(recipients)
username = config.get('email', 'username')
passwd = config.get('email', 'password')
instances = {}
for key, vals in tags.items():
for val in vals:
instances.update({val: filter_by_tag(key, [val])})
print instances
for team, details in instances.items():
subject, body = draft_email(team, details)
print body
send_email(username, passwd, recipients[team], subject, body)
if __name__ == '__main__':
run()