Sending Cloud Monitor Events to Slack through Function Compute

Prerequisites

Create Slack Web App Hook

Create Function Compute Code

# -*- 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'

Link up CloudMonitor with Function Compute Code

{
"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"
}

Further Improvements

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store