Skip to content

Commit dd33a6d

Browse files
committed
Slack
1 parent 56b72bf commit dd33a6d

File tree

5 files changed

+175
-0
lines changed

5 files changed

+175
-0
lines changed

ThirdParty/Slack/README.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# Creating Slack Notifications for CloudWatch Alarms
2+
3+
## Configure WebHook in Slack
4+
5+
1. Create a Slack App: <https://api.slack.com/apps/new>
6+
1. Search for and select **Incoming WebHooks**.
7+
1. Set **Activate Incoming Webhooks** to **On**.
8+
1. Select **Add New Webhook to Workspace**.
9+
1. Choose the default channel where messages will be sent and click **Authorize**.
10+
1. Note the webhook URL from the **Webhook URLs for Your Workspace** section. For example, `https://hooks.slack.com/services/T0HABCGK/BDEFG93SS/BeBSKJHDHmWwyv2SYV4apv1O`
11+
12+
F
13+
14+
```sh
15+
WEBHOOK_URL=https://hooks.slack.com/services/T0HABCGK/BDEFG93SS/BeBSKJHDHmWwyv2SYV4apv1O
16+
```
17+
18+
Test the webhook:
19+
20+
```sh
21+
curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' $WEBHOOK_URL
22+
```
23+
24+
## Create an SNS Topic
25+
26+
```sh
27+
aws sns create-topic --name high-cpu-alarm
28+
```
29+
30+
Note the `TopicArn`.
31+
32+
## Create CloudWatch Alarm
33+
34+
Send notification to SNS topic when CPU utilization > 40%:
35+
36+
```sh
37+
aws cloudwatch put-metric-alarm \
38+
--alarm-name cpu-mon \
39+
--alarm-description "Alarm when CPU exceeds 40%" \
40+
--metric-name CPUUtilization \
41+
--namespace AWS/EC2 \
42+
--statistic Average \
43+
--period 60 \
44+
--evaluation-periods 1 \
45+
--threshold 40 \
46+
--comparison-operator GreaterThanThreshold \
47+
--dimensions Name=InstanceId,Value=i-12345678901234567 \
48+
--alarm-actions arn:aws:sns:us-east-1:123456789012:high-cpu-alarm \
49+
--unit Percent
50+
```
51+
52+
## Create SSM Parameter
53+
54+
```sh
55+
aws ssm put-parameter --cli-input-json '{"Type": "SecureString", "KeyId": "alias/aws/ssm", "Name": "SlackWebHookURL", "Value": "'"$WEBHOOK_URL"'"}'
56+
```
57+
58+
## Create Lambda Execution Role
59+
60+
Attach the following managed policies:
61+
62+
- AmazonSSMFullAccess
63+
- AWSLambdaBasicExecutionRole
64+
65+
## Create Lambda Function
66+
67+
Use the SNS topic as a trigger.
68+
69+
## Stress the CPU
70+
71+
```sh
72+
# Install Extra Packages for Enterprise Linux
73+
sudo amazon-linux-extras install epel
74+
# Install stress
75+
sudo yum install -y stress
76+
# Beat it up for 5 mins
77+
stress --cpu 2 --timeout 300s
78+
```
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"Version": "2012-10-17",
3+
"Statement": [{
4+
"Effect": "Allow",
5+
"Action": [
6+
"kms:Decrypt"
7+
],
8+
"Resource": [
9+
"<your KMS key ARN>"
10+
]
11+
}]
12+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import json
2+
from urllib.error import HTTPError, URLError
3+
from urllib.request import Request, urlopen
4+
5+
import boto3
6+
7+
ssm = boto3.client('ssm')
8+
9+
10+
def lambda_handler(event, context):
11+
print(json.dumps(event))
12+
13+
message = json.loads(event['Records'][0]['Sns']['Message'])
14+
print(json.dumps(message))
15+
16+
alarm_name = message['AlarmName']
17+
new_state = message['NewStateValue']
18+
reason = message['NewStateReason']
19+
20+
slack_message = {
21+
'text': f':fire: {alarm_name} state is now {new_state}: {reason}\n'
22+
f'```\n{message}```'
23+
}
24+
25+
webhook_url = ssm.get_parameter(
26+
Name='SlackWebHookURL', WithDecryption=True)
27+
28+
req = Request(webhook_url['Parameter']['Value'],
29+
json.dumps(slack_message).encode('utf-8'))
30+
31+
try:
32+
response = urlopen(req)
33+
response.read()
34+
print(f"Message posted to Slack")
35+
except HTTPError as e:
36+
print(f'Request failed: {e.code} {e.reason}')
37+
except URLError as e:
38+
print(f'Server connection failed: {e.reason}')

ThirdParty/Slack/sample_alarm.json

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{
2+
"AlarmName": "cpu-mon",
3+
"AlarmDescription": "Alarm when CPU exceeds 40%",
4+
"AWSAccountId": "123456789012",
5+
"NewStateValue": "ALARM",
6+
"NewStateReason": "Threshold Crossed: 1 datapoint [99.0 (18/03/19 18:06:00)] was greater than or equal to the threshold (40.0).",
7+
"StateChangeTime": "2019-03-18T18:11:58.507+0000",
8+
"Region": "US East (Ohio)",
9+
"OldStateValue": "OK",
10+
"Trigger": {
11+
"MetricName": "CPUUtilization",
12+
"Namespace": "AWS/EC2",
13+
"StatisticType": "Statistic",
14+
"Statistic": "AVERAGE",
15+
"Unit": null,
16+
"Dimensions": [{
17+
"value": "i-12345678901234567",
18+
"name": "InstanceId"
19+
}],
20+
"Period": 300,
21+
"EvaluationPeriods": 1,
22+
"ComparisonOperator": "GreaterThanOrEqualToThreshold",
23+
"Threshold": 40,
24+
"TreatMissingData": "",
25+
"EvaluateLowSampleCountPercentile": ""
26+
}
27+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"Records": [{
3+
"EventSource": "aws:sns",
4+
"EventVersion": "1.0",
5+
"EventSubscriptionArn": "arn:aws:sns:us-east-2:123456789012:high-cpu-alarm:37113ff5-bc0f-47e7-93cb-a568393b1cdf",
6+
"Sns": {
7+
"Type": "Notification",
8+
"MessageId": "c5185dee-b948-5a60-8240-08e75ff37af7",
9+
"TopicArn": "arn:aws:sns:us-east-2:123456789012:high-cpu-alarm",
10+
"Subject": "ALARM: \"cpu-mon\" in US East (Ohio)",
11+
"Message": "{\"AlarmName\":\"cpu-mon\",\"AlarmDescription\":\"Alarm when CPU exceeds 40%\",\"AWSAccountId\":\"123456789012\",\"NewStateValue\":\"ALARM\",\"NewStateReason\":\"Threshold Crossed: 1 datapoint [99.66666666666667 (18/03/19 18:28:00)] was greater than or equal to the threshold (40.0).\",\"StateChangeTime\":\"2019-03-18T18:33:31.823+0000\",\"Region\":\"US East (Ohio)\",\"OldStateValue\":\"OK\",\"Trigger\":{\"MetricName\":\"CPUUtilization\",\"Namespace\":\"AWS/EC2\",\"StatisticType\":\"Statistic\",\"Statistic\":\"AVERAGE\",\"Unit\":null,\"Dimensions\":[{\"value\":\"i-0bae13e726155adc3\",\"name\":\"InstanceId\"}],\"Period\":300,\"EvaluationPeriods\":1,\"ComparisonOperator\":\"GreaterThanOrEqualToThreshold\",\"Threshold\":40.0,\"TreatMissingData\":\"\",\"EvaluateLowSampleCountPercentile\":\"\"}}",
12+
"Timestamp": "2019-03-18T18:33:31.872Z",
13+
"SignatureVersion": "1",
14+
"Signature": "WiZ8lP42Gu7VHwgBWW1wuXtYlP5why37F5BV/8jxhNmdJVLjwdqbP6lEmPrvz3qNnhxly5P2UPGqCkB6B6U1HCXR+9Xt4td9boMs9mf3zAkC93rJbnUEkURmuIcSqlaSZ0odPK/53VCR3mYkQUc9nkOVBVvlrIAFhx8EtUme7MHV0sju1pchkunTECv9cSmbn9TP2SNkai+KIRfzFSXA7aEsr1m/VbLrzIAynWtxRdO+hksZdkFXd8pm3R5B6ElipuiIErQbVjF9hc7ytFqxIZBP8b5Vpq8ecaoV2g87zuZ7p+bY118td95IT6f9xATMZuv1hwm4LwRn5SukWQ+EQw==",
15+
"SigningCertUrl": "https://sns.us-east-2.amazonaws.com/SimpleNotificationService-6aad65c2f9911b05cd53efda11f913f9.pem",
16+
"UnsubscribeUrl": "https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-2:123456789012:high-cpu-alarm:37113ff5-bc0f-47e7-93cb-a568393b1cdf",
17+
"MessageAttributes": {}
18+
}
19+
}]
20+
}

0 commit comments

Comments
 (0)