-
Notifications
You must be signed in to change notification settings - Fork 0
/
bearychat.py
58 lines (44 loc) · 1.6 KB
/
bearychat.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
#!/usr/bin/env python3
import boto3
from botocore.vendored import requests
BEARYCHAT_WEBHOOK = '<Your BearyChat Webhook>'
BEARYCHAT_CHANNEL = '<Your BearyChat Channel>'
def get_aws_console_domain(region):
if region.startswith('cn-'):
return 'console.amazonaws.cn'
else:
return 'console.aws.amazon.com'
def get_instance_url(instance_id, region):
domain = get_aws_console_domain(region)
return (f'https://{domain}/ec2/v2/home'
f'?region={region}'
f'#Instances:instanceId={instance_id}')
def get_instance_name(instance_id, region):
ec2 = boto3.resource('ec2', region_name=region)
instance = ec2.Instance(instance_id)
name = None
for tags in instance.tags:
if tags['Key'] == 'Name':
name = tags['Value']
return name
def send_bearychat(payload):
r = requests.post(BEARYCHAT_WEBHOOK, json=payload)
return r.text
def make_bearychat_payload(event):
region = event['region']
state = event['detail']['state']
instance_id = event['detail']['instance-id']
instance_url = get_instance_url(instance_id, region)
name = get_instance_name(instance_id, region)
name = f' ({name})' if name else ''
text = f'EC2 ({region}) **{state}**: [{instance_id}]({instance_url}){name}'
# https://github.com/bearyinnovative/bearychat-docs/blob/master/tutorials/markdown/incoming.md
payload = dict(
channel=BEARYCHAT_CHANNEL,
markdown=True,
text=text,
)
return payload
def lambda_handler(event, context):
payload = make_bearychat_payload(event)
return send_bearychat(payload)