Webhook using Cloud Functions
To automate processing of incidents and other events in your cloud, Yandex Monitoring supports invoking functions in Cloud Functions. This section provides an example of a webhook configured to send POST requests when an alert triggers. This means you can use alerts to call external API methods. You can also use escalations to invoke functions in Cloud Functions.
To send POST requests when an alert triggers:
-
Deploy the service for POST request processing with the following attributes:
https://my.url/route/for/alarm
: URL to process a request when the alert gets theAlarm
status.https://my.url/route/for/ok
: URL to process a request when the alert gets theOk
status.my_secret_token
: Token or token file for call authorization.
You can test the function without deploying the POST request processing service. In this case, when sending a request, the function call logs will display a message saying the specified URL is unavailable.
-
Create a service account to invoke your function.
-
Create a function sending POST requests when the alert gets the
Alarm
orOk
status. -
Create a channel that will invoke the function.
-
Create an alert that will send notifications to the channel with your function.
Creating a service account
- In the management console
, go to the folder containing the resources you need to track in Monitoring. - From the list of services, select Identity and Access Management.
- Click Create service account.
- Enter a name for the service account, e.g.,
sa-alert-webhook
. - Add the
functions.functionInvoker
andfunctions.viewer
roles. - Click Create.
Creating a function
-
From the list of services, select Cloud Functions.
-
Click Create function.
-
Enter a name for the function, e.g.,
alert-webhook
. -
Click Create.
-
Create a function version:
-
Select the Python runtime environment, disable the Add files with code examples option, and click Continue.
-
Choose the Code editor method.
-
Click Create file and specify a file name, e.g.,
index
. -
Enter the function code by specifying the URL for processing POST requests and the token:
import json import requests WEBHOOK_ALARM_URL = "https://my.url/route/for/alarm" WEBHOOK_OK_URL = "https://my.url/route/for/ok" WEBHOOK_AUTH_TOKEN = "my_secret_token" def webhook(url, alert_id): headers_ = { "Authorization": f"OAuth {WEBHOOK_AUTH_TOKEN}", "Content-type": "application/json" } try: response = requests.post(url, headers = headers_, json = { "alert_id" : alert_id }) if response.ok: return { "status": "OK", "url": url, "response": json.dumps(response.json)} else: return { "status": "ERROR", "url": url, "code": response.status_code, "error": response.text} except Exception as e: return { "status": "EXCEPTION", "url": url, "error": e} def handler(event, context): alert = event # For convenience, save the event to the alert variable. required_attributes = ["alertId", "status"] # Array of required input parameters in JSON format. # If the function input is not JSON or has missing required parameters, the function will not run. if not alert or all(attr in required_attributes for attr in alert): return result = None # If the function is invoked when the alert status is ALARM, send a request to WEBHOOK_ALARM_URL. # If the function is invoked when the alert status is OK, send a request to WEBHOOK_OK_URL. # Do not invoke the function in case of other alert statuses. if alert["status"] == "ALARM": result = webhook(WEBHOOK_ALARM_URL, alert["alertId"]) elif alert["status"] == "OK": result = webhook(WEBHOOK_OK_URL, alert["alertId"]) else: pass if not result: return # Output the call result to the log if result["status"] == "OK": print(f"Succesffully invoked {result['url']}. Response: {result['response']}") elif result["status"] == "ERROR": print(f"ERROR invoking {result['url']}. Code {result['code']}, error message: {result['error']}") else: print(f"{result['status']} when invoking {result['url']}. Error message: {result['error']}")
-
-
Under Parameters, set the version parameters:
- Entry point:
index.handler
- Service account:
sa-alert-webhook
- Entry point:
-
Under Additional settings, enable Asynchronous call.
-
Click Save changes.
Creating a channel
- Select Monitoring.
- Go to the Notification channels section.
- Click Create channel.
- Enter a name for your notification channel, e.g.,
channel-function
. - From the Method list, select Cloud Functions.
- From the Service account list, select the account you created when adding your function.
- Click Create.
Creating an alert
- In Monitoring, select Alerts.
- Click Create.
- Enter a name for the alert, e.g.,
alert-function
. - Enter the query to use for selecting which metrics to track.
- Configure the trigger conditions.
- Under Notifications, click Edit and then Add.
- Select
channel-function
. - Click Add.
- Click Create.
Testing function invocation
-
From the list of services, select Cloud Functions.
-
Select the
alert-webhook
function. -
Select the Testing tab.
-
As input data, enter:
{ "alertId": "<alert_ID>", "alertName": "alert-function", "folderId": "<folder_ID>", "status": "OK" }
-
Click Run test.
-
In the function call logs, in the Testing or Logs tab, make sure the request was sent to this URL:
https://my.url/route/for/ok
.