forked from robbwagoner/aws-lambda-sns-to-slack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
executable file
·258 lines (234 loc) · 8.03 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
#!/usr/bin/env python
'''
Parse an SNS event message and send to a Slack Channel
'''
from __future__ import print_function
import boto3
import json
import re
import requests
from base64 import b64decode
__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__ = "robb@pandastrike.com"
__status__ = "Production"
DEFAULT_USERNAME = 'AWS Lambda'
DEFAULT_CHANNEL = '#webhook-tests'
def get_slack_emoji(event_src, event_sev, 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:'}},
'elasticache': {
'notices': {'default': ':stopwatch:'}},
'rds': {
'notices': {'default': ':registered:'}}}
try:
return emoji_map[event_src][event_sev][event_cond]
except KeyError:
if event_sev == 'alerts':
return ':fire:'
else:
return ':information_source:'
def get_slack_username(event_src):
'''Map event source to the Slack username
'''
username_map = {
'cloudwatch': 'AWS CloudWatch',
'autoscaling': 'AWS AutoScaling',
'elasticache': 'AWS ElastiCache',
'rds': 'AWS RDS'}
try:
return username_map[event_src]
except KeyError:
return DEFAULT_USERNAME
def get_slack_channel(region, event_src, event_env, event_sev):
'''Map region and event type to Slack channel name
'''
if event_src == 'autoscaling':
event_map = {
'notices': 'autoscaling',
'alerts': 'alerts'}
else:
event_map = {
'notices': 'events',
'events': 'events',
'alerts': 'alerts'}
channel_map = {
'production': '#{}-{}'.format(event_map[event_sev], region),
'staging': '#staging-notifications'}
try:
return channel_map[event_env]
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
'''
with open('config.json') as f:
config = json.load(f)
event_cond = 'default'
sns = event['Records'][0]['Sns']
print('DEBUG:', sns['Message'])
json_msg = json.loads(sns['Message'])
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": "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', '')):
event_src = 'rds'
attachments = [{
"fields": [{
"title": "Source",
"value": json_msg['Event Source']
},{
"title": "Message",
"value": json_msg['Event Message']
}]}]
if json_msg.get('Identifier Link'):
attachments.append({
"text": "Details",
"title": json_msg['Identifier Link'].split('\n')[1],
"title_link": json_msg['Identifier Link'].split('\n')[0]})
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)
WEBHOOK_URL = "https://" + boto3.client('kms').decrypt(
CiphertextBlob=b64decode(config['encrypted_webhook_url']))['Plaintext']
payload = {
'text': message,
'channel': get_slack_channel(region, event_src, event_env, event_sev),
'username': get_slack_username(event_src),
'icon_emoji': get_slack_emoji(event_src, event_sev, event_cond.lower())}
if attachments:
payload['attachments'] = attachments
print('DEBUG:', payload)
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"
}
}
]
}""")
print('running locally')
print(lambda_handler(sns_event_template, None))