-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction.py
62 lines (52 loc) · 1.95 KB
/
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
from datetime import datetime, timedelta
import os
from dateutil.tz import gettz
import json
import boto3
import urllib.request
diff_hours = int(os.environ["DIFF_HOURS"])
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
now = datetime.utcnow()
target_time = now + timedelta(hours=-diff_hours)
ec2_instances = []
ec2_data = ec2.describe_instances()
for ec2_reservation in ec2_data['Reservations']:
for ec2_instance in ec2_reservation['Instances']:
if ec2_instance["State"]["Code"] != 80 and ec2_instance["LaunchTime"].astimezone() < target_time.astimezone():
ec2_instances.append(ec2_instance)
notify_targets = []
for ec2_instance in ec2_instances:
name = "-"
ignore = False
for tag in ec2_instance["Tags"]:
if tag["Key"] == "Name":
name = tag["Value"]
if tag["Key"] == "ec2-checker":
ignore = tag["Value"] == "0"
if ignore:
continue
notify_targets.append([{
"title": "インスタンス",
"value": name,
"short": True
}, {
"title": "起動時刻",
"value": ec2_instance["LaunchTime"].astimezone(gettz('Asia/Tokyo')).strftime('%Y/%m/%d %H:%M:%S'),
"short": True
}])
if len(notify_targets) > 0:
body = {
"text": f"起動時間が{diff_hours}時間を超えているEC2インスタンスがあります",
"attachments": []
}
for notify_target in notify_targets:
body["attachments"].append({
"color": "danger",
"fields": notify_target
})
req = urllib.request.Request(os.environ["SLACK_WEBHOOK_URL"],
data=json.dumps(body).encode('utf-8'),
method='POST')
res = urllib.request.urlopen(req)
return notify_targets