×
Community Blog Sending Cloud Monitor Events to Slack through Function Compute

Sending Cloud Monitor Events to Slack through Function Compute

In this blog, we will show the necessary steps to integrate Alibaba Cloud Monitor's event monitoring capability and create event notifications using Slack.

By Kenny Lai, Solutions Architect

Slack is a cloud-based set of proprietary team collaboration tools and services, best known for their enterprise messaging app. Although most customers use it as a basic communication channel between co-workers within a company, Slack is capable of a lot more. For instance, it can be integrated with many system monitoring tools to provide a platform for receive monitoring notification.

In this blog, we will show the necessary steps in order to integrate Alibaba Cloud's Cloud Monitor event monitoring capability on Slack to create notification of events using Function Compute.

Prerequisites

  1. A Slack account.
  2. An Alibaba Cloud account.

Create Slack Web App Hook

1.  Create Slack App Webhook

2.  Visit https://api.slack.com/slack-apps to start create a Slack App.

1

3.  Click "Create a Slack app", it will move to Your Apps page

2

4.  Click "Create New App", name the App as "Alicloud Monitoring" in this example. Select the Test workspace and click "Create App"

3

5.  Add incoming Webhooks Feature to the app

4

6.  Activate Incoming Webhooks by clicking the off switch

5\

7.  Click Add New Webhook to Workspace

6

8.  Select which Channel to post the message to.

7

9.  Get the Webhook URL by clicking on the Copy icon

8

Configuration of Slack is done and copy the webhook URL as it will use in the step below

Create Function Compute Code

1.  Create a Function Compute project.

2.  Identify Function Compute console by searching "function compute" via search function.

9

3.  Click on the + icon to create a new Function Compute Project (choose the right region before you click the + icon)

10

4.  Type in the Service Name and click ok. In this example, we name the Service as CM2Slack

11

5.  Click on + size to create a new Functions

12

6.  Select the Empty Function Template

13

7.  It will move to next step and select "No Trigger" as Trigger Type and click Next

14

8.  Type the Function Name (In this example, we call it "fc-call-back" and choose python3 as Runtime).

15

9.  Paste the following code in to the in-line Edit page

# -*- coding: utf-8 -*-
import logging
import requests
import json

# if you open the initializer feature, please implement the initializer function, as below:
# def initializer(context):
#   logger = logging.getLogger()
#   logger.info('initializing')

def handler(event, context):
  logger = logging.getLogger()
  #logger.info('hello world')
  evt = json.loads(event)
  level = evt.get("level")
  name = evt.get("name")
  end_url = 'https://hooks.slack.com/services/balabalablabalbaa'
  headers = {'Content-type': 'application/json'}
  msg = "event: {} [{}]".format(name,level)
  payload = {'text': msg}
  logger.info("level : "+level+"\nname : "+name)
  r = requests.post(end_url,headers=headers, data=json.dumps(payload))
  
  return 'ok' 

Note: modify the end_url to the actual value of the slack webhook callback url

10.  In Runtime Environment Section, choose the Memory size with 128MB and click Next

16

11.  Click Next to skip the Service Role Management as this code doesn't require access to other cloud service.

17

12.  Click Create to create the function

18

13.  The fc code is created and next step is to configurate cloud monitor to trigger the fc code

Link up CloudMonitor with Function Compute Code

1.  Identify CloudMonitor console via keyword search

19

2.  Go to Event Monitoring, then Alarm Rules

20

3.  Click Customer Events Tab and Click "Create event alerts"

21

4.  Enter the basic info. In this example, we name the alert "autoscale_alert" for event name. In order to test the alarm, please select only one of the events and after testing, select all the events that needs to be monitored.

For Product Type, Select Auto Scaling (for list of product and event support, please refer to https://www.alibabacloud.com/help/doc-detail/66940.htm)

22

5.  Scroll down and check Function service

23

6.  Select correct region, service and function name (In this example, select CM2Slack and fc-call-back as function name) and click ok

24

7.  Test the alert by click on test link

25

8.  A Test event page will pop up and past the following JSON into the text box and click OK

26

Content (JSON)

{
    "product": "ESS",
    "content": {
        "startTime": "2018-08-16T08:39:38.000Z",
        "instanceIds": [
            "i-m5e0pe3xy3tj21aaq1er"
        ],
        "totalCapacity": 1,
        "scalingActivityId": "asa-m5eavvsbsndub3vanzeu",
        "expectNum": 1,
        "cause": "A user requests to execute scaling rule \"asr-m5eb6o1bd1mde0og7msb\", changing the Total Capacity from \"0\" to \"1\".",
        "requestId": "603EDEA2-CF9F-431A-975F-31296EA68CD7",
        "description": "\"1\" ECS instances are added",
        "scalingRuleId": "asr-m5eb6o1bd1mde0og7msb",
        "endTime": "2018-08-16T08:40:46.000Z"
    },
    "resourceId": "acs:<service-name>:<region>:<account-id>:<resource-relative-id>",
    "level": "INFO",
    "instanceName": "instanceName",
    "status": "normal",
    "name": "AUTOSCALING:SCALE_OUT_SUCCESS",
    "regionId": "cn-hangzhou"
} 

9.  Switch to Slack and see the message is being pushed

27

Further Improvements

To create more meaningful alert messages, try to make use of different variable stored in evt object.

The event object contains product name, resourceId, level, name,regionId and other meaningful data

msg = "event: {} [{}]".format(name,level)
payload = {'text': msg} 
0 0 0
Share on

Alibaba Clouder

1,496 posts | 242 followers

You may also like

Comments

Alibaba Clouder

1,496 posts | 242 followers

Related Products