forked from alerta/alerta-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alerta_sns.py
69 lines (51 loc) · 2.36 KB
/
alerta_sns.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
import boto.exception
import boto.sns
import logging
import os
try:
from alerta.plugins import app # alerta >= 5.0
except ImportError:
from alerta.app import app # alerta < 5.0
from alerta.plugins import PluginBase
LOG = logging.getLogger('alerta.plugins.sns')
DEFAULT_AWS_REGION = 'eu-west-1'
DEFAULT_AWS_SNS_TOPIC = 'notify'
AWS_REGION = os.environ.get('AWS_REGION') or app.config.get('AWS_REGION', DEFAULT_AWS_REGION)
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') or app.config.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') or app.config.get('AWS_SECRET_ACCESS_KEY')
AWS_SNS_TOPIC = os.environ.get('AWS_SNS_TOPIC') or app.config.get('AWS_SNS_TOPIC', DEFAULT_AWS_SNS_TOPIC)
class SnsTopicPublisher(PluginBase):
def __init__(self, name=None):
try:
self.connection = boto.sns.connect_to_region(
region_name=AWS_REGION,
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)
except Exception as e:
LOG.error('Error connecting to SNS topic %s: %s', AWS_SNS_TOPIC, e)
raise RuntimeError
if not self.connection:
LOG.error('Failed to connect to SNS topic %s - check AWS credentials and region', AWS_SNS_TOPIC)
raise RuntimeError
try:
response = self.connection.create_topic(AWS_SNS_TOPIC)
except boto.exception.BotoServerError as e:
LOG.error('Error creating SNS topic %s: %s', AWS_SNS_TOPIC, e)
raise RuntimeError
try:
self.topic_arn = response['CreateTopicResponse']['CreateTopicResult']['TopicArn']
except KeyError:
LOG.error('Failed to get SNS TopicArn for %s', AWS_SNS_TOPIC)
raise RuntimeError
super(SnsTopicPublisher, self).__init__(name)
LOG.info('Configured SNS publisher on topic "%s"', self.topic_arn)
def pre_receive(self, alert):
return alert
def post_receive(self, alert):
LOG.info('Sending message %s to SNS topic "%s"', alert.get_id(), self.topic_arn)
LOG.debug('Message: %s', alert.get_body())
response = self.connection.publish(topic=self.topic_arn, message=alert.get_body())
LOG.debug('Response: %s', response)
def status_change(self, alert, status, text):
return