-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathperiodic_lambda_function.py
executable file
·85 lines (64 loc) · 2.29 KB
/
periodic_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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3
import boto3
import json
import io
def lambda_handler(event, context):
print(event)
running_instances = {}
for region in event["regions"]:
ec2client = boto3.client('ec2', region)
try:
response = ec2client.describe_instances()
except Exception as e:
print("Error fetching instances from region " + region)
print(e)
continue
running_instances[region] = []
for resp in response["Reservations"]:
for instance in resp["Instances"]:
if instance["State"]["Name"] == "running":
for tag in instance["Tags"]:
if tag["Key"] == "Name":
if tag["Value"].startswith("team-czcpt"):
break
running_instances[region].append(tag["Value"])
running_instances[region].sort()
instances_formatted = build_instance_email_text(running_instances)
send_email(event["recipients"], event["fromemail"], instances_formatted, event["emailregion"])
return {
'statusCode': 200,
'body': json.dumps('Lambda complete!')
}
def build_instance_email_text(instances):
buf = io.StringIO()
for region in instances.keys():
if len(instances[region]) == 0:
continue
buf.write("Region: {}\n".format(region))
for instance in instances[region]:
buf.write("{}\n".format(instance))
buf.write("\n")
return buf.getvalue()
def send_email(recipients, fromemail, email_body, region):
sesclient = boto3.client('ses', region)
response = sesclient.send_email(
Source=fromemail,
Destination={
'ToAddresses': recipients,
},
Message={
'Subject': {'Data': 'Hive running instance report'},
'Body': {'Text': {'Data': email_body}},
},
)
print("Email response: {}".format(response))
def main():
event = {"regions": ["us-east-1", "us-east-2"],
"recipients": ["[email protected]"],
"fromemail": "[email protected]",
"emailregion": "us-east-1",
}
result = lambda_handler(event, "")
print(result)
if __name__ == "__main__":
main()