forked from builtinnya/aws-sns-slack-terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lambda_function.py
345 lines (317 loc) · 11.3 KB
/
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
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#!/usr/bin/env python
#
# Copyright (c) 2017 Naoto Yokoyama
#
# Modifications applied to the original work.
#
#
# Original copyright notice:
#
# Copyright 2015 Robb Wagoner
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
'''
Parse an SNS event message and send to a Slack Channel
'''
import os
import json
import base64
import re
import requests
from base64 import b64decode
from pprint import pprint
__author__ = "Robb Wagoner (@robbwagoner)"
__copyright__ = "Copyright 2015 Robb Wagoner"
__credits__ = ["Robb Wagoner"]
__license__ = "Apache License, 2.0"
__version__ = "0.1.2"
__maintainer__ = "Robb Wagoner"
__email__ = "[email protected]"
__status__ = "Production"
DEFAULT_USERNAME = os.environ.get('DEFAULT_USERNAME', 'AWS Lambda')
DEFAULT_CHANNEL = os.environ.get('DEFAULT_CHANNEL', '#webhook-tests')
DEFAULT_EMOJI = os.environ.get('DEFAULT_EMOJI', ':information_source:')
USERNAME_PREFIX = os.environ.get('USERNAME_PREFIX', '')
SNS_EVENT_MESSAGE_TEMPLATE = os.environ.get('SNS_EVENT_MESSAGE_TEMPLATE', '')
def get_slack_emoji(event_src, topic_name, event_cond='default'):
'''Map an event source, severity, and condition to an emoji
'''
emoji_map = {
'autoscaling': {
'notices': {'default': ':scales:'}},
'cloudwatch': {
'notices': {
'ok': ':ok:',
'alarm': ':fire:',
'insuffcient_data': ':question:'},
'alerts': {
'ok': ':ok:',
'alarm': ':fire:',
'insuffcient_data': ':question:'}},
'codepipeline': {
'notices': {
'STARTED': ':ok:',
'FAILED': ':fire:',
'SUCCEEDED': ':ok:'}},
'elasticache': {
'notices': {'default': ':stopwatch:'}},
'rds': {
'notices': {'default': ':registered:'}}}
try:
return emoji_map[event_src][topic_name][event_cond]
except KeyError:
if topic_name == 'alerts':
return ':fire:'
else:
return DEFAULT_EMOJI
def get_slack_username(event_src):
'''Map event source to the Slack username
'''
username_map = {
'cloudwatch': 'AWS CloudWatch',
'autoscaling': 'AWS AutoScaling',
'elasticache': 'AWS ElastiCache',
'codepipeline': 'AWS CodePipeline',
'rds': 'AWS RDS'}
try:
return "{0}{1}".format(USERNAME_PREFIX, username_map[event_src])
except KeyError:
return DEFAULT_USERNAME
def get_slack_channel(region, event_src, topic_name, channel_map):
'''Map region and event type to Slack channel name
'''
try:
return channel_map[topic_name]
except KeyError:
return DEFAULT_CHANNEL
def autoscaling_capacity_change(cause):
'''
'''
s = re.search(r'capacity from (\w+ to \w+)', cause)
if s:
return s.group(0)
def lambda_handler(event, context):
'''The Lambda function handler
'''
config = {
'webhook_url': os.environ['WEBHOOK_URL'],
'channel_map': json.loads(base64.b64decode(os.environ['CHANNEL_MAP']))
}
event_cond = 'default'
sns = event['Records'][0]['Sns']
print('DEBUG EVENT:', sns['Message'])
try:
json_msg = json.loads(sns['Message'])
except ValueError as e:
json_msg = {}
if sns['Subject']:
message = sns['Subject']
else:
message = sns['Message']
# https://api.slack.com/docs/attachments
attachments = []
if json_msg.get('AlarmName'):
event_src = 'cloudwatch'
event_cond = json_msg['NewStateValue']
color_map = {
'OK': 'good',
'INSUFFICIENT_DATA': 'warning',
'ALARM': 'danger'
}
attachments = [{
'fallback': json_msg,
'message': json_msg,
'color': color_map[event_cond],
"fields": [{
"title": "Alarm",
"value": json_msg['AlarmName'],
"short": True
}, {
"title": "Status",
"value": json_msg['NewStateValue'],
"short": True
}, {
"title": "Description",
"value": json_msg['AlarmDescription'],
"short": False
}, {
"title": "Reason",
"value": json_msg['NewStateReason'],
"short": False
}]
}]
elif json_msg.get('Cause'):
event_src = 'autoscaling'
attachments = [{
"text": "Details",
"fallback": message,
"color": "good",
"fields": [{
"title": "Capacity Change",
"value": autoscaling_capacity_change(json_msg['Cause']),
"short": True
}, {
"title": "Event",
"value": json_msg['Event'],
"short": False
}, {
"title": "Cause",
"value": json_msg['Cause'],
"short": False
}]
}]
elif json_msg.get('ElastiCache:SnapshotComplete'):
event_src = 'elasticache'
attachments = [{
"text": "Details",
"fallback": message,
"color": "good",
"fields": [{
"title": "Event",
"value": "ElastiCache Snapshot"
}, {
"title": "Message",
"value": "Snapshot Complete"
}]
}]
elif re.match("RDS", sns.get('Subject') or ''):
event_src = 'rds'
attachments = [{
"fields": [{
"title": "Source",
"value": "{0} '{1}'".format(json_msg['Event Source'], json_msg['Source ID'])
},{
"title": "Message",
"value": json_msg['Event Message']
}]}]
if json_msg.get('Identifier Link'):
title_arr = json_msg['Identifier Link'].split('\n')
if len(title_arr) >= 2:
title_str = title_arr[1]
title_lnk_str = title_arr[0]
else:
title_str = title_lnk_str = title_arr[0]
attachments[0]['fields'].append({
"title": "Details",
"value": "<{0}|{1}>".format(title_str, title_lnk_str)
})
elif json_msg.get('source') == 'aws.codepipeline':
event_src = 'codepipeline'
message = json_msg.get('detail-type')
event_cond = json_msg.get('detail').get('state')
color_map = {
'STARTED': 'good',
'SUCCEEDED': 'good',
'FAILED': 'danger'
}
attachments = [{
'fallback': json_msg.get('detail-type'),
'color': color_map[event_cond],
"fields": [{
"title": "Pipeline",
"value": json_msg.get('detail').get('pipeline')
}, {
"title": "State",
"value": json_msg.get('detail').get('state')
}]
}]
elif json_msg.get('Records')[0].get('eventSource') == 'aws:s3':
event_src = 's3'
event_records = json_msg.get('Records')[0]
event_records_s3 = event_records.get('s3')
attachments = [{
"fields": [{
"title": "eventName",
"value": event_records.get('eventName'),
"short": True
}, {
"title": "s3 bucket",
"value": event_records_s3.get('bucket').get('name'),
"short": True
}, {
"title": "s3 object key",
"value": event_records_s3.get('object').get('key'),
"short": True
}, {
"title": "s3 object size",
"value": event_records_s3.get('object').get('size'),
"short": True
}]
}]
else:
event_src = 'other'
# SNS Topic ARN: arn:aws:sns:<REGION>:<AWS_ACCOUNT_ID>:<TOPIC_NAME>
#
# SNS Topic Names => Slack Channels
# <env>-alerts => alerts-<region>
# <env>-notices => events-<region>
#
region = sns['TopicArn'].split(':')[3]
topic_name = sns['TopicArn'].split(':')[-1]
# event_env = topic_name.split('-')[0]
# event_sev = topic_name.split('-')[1]
# print('DEBUG:', topic_name, region, event_env, event_sev, event_src)
channel_map = config['channel_map']
payload = {
'text': message,
'channel': get_slack_channel(region, event_src, topic_name, channel_map),
'username': get_slack_username(event_src),
'icon_emoji': get_slack_emoji(event_src, topic_name, event_cond.lower())}
if attachments:
payload['attachments'] = attachments
print('DEBUG PAYLOAD:', json.dumps(payload))
webhook_url = config['webhook_url'] if re.match('^https://', config['webhook_url']) else f"https://{config['webhook_url']}"
r = requests.post(webhook_url, json=payload)
return r.status_code
# Test locally
if __name__ == '__main__':
sns_event_template = json.loads(r"""
{
"Records": [
{
"EventVersion": "1.0",
"EventSubscriptionArn": "arn:aws:sns:EXAMPLE",
"EventSource": "aws:sns",
"Sns": {
"SignatureVersion": "1",
"Timestamp": "1970-01-01T00:00:00.000Z",
"Signature": "EXAMPLE",
"SigningCertUrl": "EXAMPLE",
"MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e",
"Message": "{\"AlarmName\":\"sns-slack-test-from-cloudwatch-total-cpu\",\"AlarmDescription\":null,\"AWSAccountId\":\"123456789012\",\"NewStateValue\":\"OK\",\"NewStateReason\":\"Threshold Crossed: 1 datapoint (7.9053535353535365) was not greater than or equal to the threshold (8.0).\",\"StateChangeTime\":\"2015-11-09T21:19:43.454+0000\",\"Region\":\"US - N. Virginia\",\"OldStateValue\":\"ALARM\",\"Trigger\":{\"MetricName\":\"CPUUtilization\",\"Namespace\":\"AWS/EC2\",\"Statistic\":\"AVERAGE\",\"Unit\":null,\"Dimensions\":[],\"Period\":300,\"EvaluationPeriods\":1,\"ComparisonOperator\":\"GreaterThanOrEqualToThreshold\",\"Threshold\":8.0}}",
"MessageAttributes": {
"Test": {
"Type": "String",
"Value": "TestString"
},
"TestBinary": {
"Type": "Binary",
"Value": "TestBinary"
}
},
"Type": "Notification",
"UnsubscribeUrl": "EXAMPLE",
"TopicArn": "arn:aws:sns:us-east-1:123456789012:production-notices",
"Subject": "OK: sns-slack-test-from-cloudwatch-total-cpu"
}
}
]
}""")
sns_event_message_template = None
if (SNS_EVENT_MESSAGE_TEMPLATE != ""):
f = open(os.path.dirname(os.path.abspath(__file__)) + '/' + SNS_EVENT_MESSAGE_TEMPLATE, 'r')
sns_event_message_template = json.load(f)
sns_event_template['Records'][0]['Sns']['Message'] = json.dumps(sns_event_message_template)
print('running locally')
print(lambda_handler(sns_event_template, None))