-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.py
More file actions
137 lines (124 loc) · 4.03 KB
/
handler.py
File metadata and controls
137 lines (124 loc) · 4.03 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import os
import datetime
import ssl
import socket
import json
import logging
import urllib.request
'''
following environment variables are available
SLACK_URL: incomming webhook url
DAYS: threshold (default: 28)
'''
DEFAULT_DAYS = 28
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def ssl_expiry_datetime(host, port=443):
ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
context = ssl.create_default_context()
conn = context.wrap_socket(
socket.socket(socket.AF_INET),
server_hostname=host,
)
conn.settimeout(5)
res = None
try:
conn.connect((host, port))
ssl_info = conn.getpeercert()
res = datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)
except socket.error as error:
logger.error('socket.error')
post_error_to_slack(error, host)
except ssl.SSLError as error:
logger.error('ssl.SSLError')
post_error_to_slack(error, host)
except:
post_error_to_slack('unexpected error', host)
return res
def post_expiry_alert_to_slack(fqdn, expiry_date, remaining_days):
slack_message = {
'icon_emoji': ':eye-in-speech-bubble:',
'text': '証明書の期限が迫っていますが自動更新が失敗しているようです',
'attachments': [{
'fallback': 'fallback text',
'fields': [
{
'title': 'FQDN',
'value': fqdn,
'short': True
},
{
'title': 'expiry date',
'value': expiry_date.strftime('%Y-%m-%d'),
'short': True
},
{
'title': '残り',
'value': '{}日'.format(remaining_days),
'short': True
},
],
'color': 'warning'
}]
}
post_to_slack(slack_message)
def post_error_to_slack(error, host='unknown'):
slack_message = {
'icon_emoji': ':eye-in-speech-bubble:',
'text': 'error occurred',
'attachments': [{
'fallback': 'fallback text',
'fields': [
{
'title': 'error',
'value': str(error),
},
{
'title': 'type',
'value': str(type(error)),
'short': True
},
{
'title': 'FQDN',
'value': host,
'short': True
}
],
'color': 'danger'
}]
}
post_to_slack(slack_message)
def post_to_slack(slack_message):
url = os.environ['SLACK_URL']
data = "payload=" + json.dumps(slack_message)
request = urllib.request.Request(url, data.encode('utf-8'))
try:
with urllib.request.urlopen(request) as response:
_response_body = response.read().decode('utf-8')
except urllib.request.HTTPError as e:
logger.error('Request failed: {} {}'.format(e.code, e.reason))
except urllib.request.URLError as e:
logger.error('Server connection failed: {}'.format(e.reason))
def lambda_handler(event, context):
if event is None or type(event) is not dict:
post_error_to_slack("event is not dictionary")
return
fqdn_list = event.get('fqdn_list', [])
if len(fqdn_list) == 0:
post_error_to_slack("event['fqdn_list'] is empty")
return
threshold_days = int(os.environ.get('DAYS', DEFAULT_DAYS))
target_list = []
for fqdn in fqdn_list:
expiry_date = ssl_expiry_datetime(fqdn)
if expiry_date is None:
continue
delta = expiry_date - datetime.datetime.now()
if delta.days < threshold_days:
target_list.append((fqdn, expiry_date, delta.days))
for fqdn, expiry_date, remaining_days in target_list:
post_expiry_alert_to_slack(fqdn, expiry_date, remaining_days)
return {
'statusCode': 200,
'body': json.dumps('done')
}