שליחת התראות ל-Slack

במאמר הזה נסביר איך לשלוח התראות לגבי תקציבים ל-Slack.

בדרך כלל, התראות לגבי תקציבים מוגדרים לשליחה באימייל. אבל אימייל הוא לא תמיד הדרך הטובה ביותר להתעדכן בעלויות בענן, במיוחד אם מדובר בתקציב קריטי שבו גם הזמן חשוב. בעזרת התראות פרוגרמטיות, אתם יכולים להעביר את ההודעות לגבי התקציבים לאמצעי תקשורת אחרים, כמו Slack.

לפני שמתחילים

לפני שמתחילים צריך לבצע את המשימות האלה:

  1. הפעלת Cloud Billing API
  2. יצירת תקציב
  3. יצירת התראות פרוגרמטיות לגבי תקציבים

הגדרת ערוץ והרשאות ב-Slack

בשלב הראשון יוצרים את סביבת העבודה ב-Slack ואת אסימוני המשתמשים שמשמשים את הבוטים כדי לשלוח קריאה ל-Slack API. אסימוני ה-API מנוהלים בכתובת https://api.slack.com/apps. תוכלו להיעזר בהוראות שבמאמר Bot Users באתר Slack.

‫הגדרת ההתראות ב-Slack.

הגדרת פונקציית Cloud Run

  1. אתם יכולים להיעזר בהוראות שבמאמר יצירה של פונקציית Cloud Run. חשוב לוודא שהגדרתם את Trigger type כך שישתמש באותו נושא Pub/Sub שהוגדר לשימוש בתקציב.

  2. מוסיפים את יחסי התלות הבאים:

    Node.js

    מעתיקים את הפרטים הבאים אל package.json:

    {
      "name": "cloud-functions-billing",
      "private": "true",
      "version": "0.0.1",
      "description": "Examples of integrating Cloud Functions with billing",
      "main": "index.js",
      "engines": {
        "node": ">=16.0.0"
      },
      "scripts": {
        "compute-test": "c8 mocha -p -j 2 test/periodic.test.js --timeout=600000",
        "test": "c8 mocha -p -j 2 test/index.test.js --timeout=5000 --exit"
      },
      "author": "Ace Nassri <[email protected]>",
      "license": "Apache-2.0",
      "dependencies": {
        "@google-cloud/billing": "^4.0.0",
        "@google-cloud/compute": "^4.0.0",
        "google-auth-library": "^9.0.0",
        "googleapis": "^143.0.0",
        "slack": "^11.0.1"
      },
      "devDependencies": {
        "@google-cloud/functions-framework": "^3.0.0",
        "c8": "^10.0.0",
        "gaxios": "^6.0.0",
        "mocha": "^10.0.0",
        "promise-retry": "^2.0.0",
        "proxyquire": "^2.1.0",
        "sinon": "^18.0.0",
        "wait-port": "^1.0.4"
      }
    }
    

    Python

    מעתיקים את הפרטים הבאים אל requirements.txt:

    slackclient==2.9.4
    google-api-python-client==2.131.0
    

  3. מעתיקים את הקוד הבא לפונקציית Cloud Run כדי לפרסם התראות לגבי תקציבים בערוץ הצ'אט ב-Slack באמצעות Slack API:

    Node.js

    const slack = require('slack');
    
    // TODO(developer) replace these with your own values
    const BOT_ACCESS_TOKEN =
      process.env.BOT_ACCESS_TOKEN || 'xxxx-111111111111-abcdefghidklmnopq';
    const CHANNEL = process.env.SLACK_CHANNEL || 'general';
    
    exports.notifySlack = async pubsubEvent => {
      const pubsubAttrs = pubsubEvent.attributes;
      const pubsubData = Buffer.from(pubsubEvent.data, 'base64').toString();
      const budgetNotificationText = `${JSON.stringify(
        pubsubAttrs
      )}, ${pubsubData}`;
    
      await slack.chat.postMessage({
        token: BOT_ACCESS_TOKEN,
        channel: CHANNEL,
        text: budgetNotificationText,
      });
    
      return 'Slack notification sent successfully';
    };

    Python

    import base64
    import json
    import os
    
    import slack
    from slack.errors import SlackApiError
    
    # See https://api.slack.com/docs/token-types#bot for more info
    BOT_ACCESS_TOKEN = "xxxx-111111111111-abcdefghidklmnopq"
    CHANNEL = "C0XXXXXX"
    
    slack_client = slack.WebClient(token=BOT_ACCESS_TOKEN)
    
    
    def notify_slack(data, context):
        pubsub_message = data
    
        # For more information, see
        # https://cloud.google.com/billing/docs/how-to/budgets-programmatic-notifications#notification_format
        try:
            notification_attr = json.dumps(pubsub_message["attributes"])
        except KeyError:
            notification_attr = "No attributes passed in"
    
        try:
            notification_data = base64.b64decode(data["data"]).decode("utf-8")
        except KeyError:
            notification_data = "No data passed in"
    
        # This is just a quick dump of the budget data (or an empty string)
        # You can modify and format the message to meet your needs
        budget_notification_text = f"{notification_attr}, {notification_data}"
    
        try:
            slack_client.api_call(
                "chat.postMessage",
                json={"channel": CHANNEL, "text": budget_notification_text},
            )
        except SlackApiError:
            print("Error posting to Slack")
    
    

  4. מוודאים שהפרמטרים הבאים של postMessage ב-Slack API מוגדרים בצורה נכונה:

    • אסימון הגישה ל-OAuth של משתמש הבוט
    • שם הערוץ

בדיקת הפונקציה

כדי לוודא שהפונקציה פועלת כמו שצריך, מבצעים את הפעולות של בדיקת פונקציית Cloud Run.

אם הפעולות בוצעו כמו שצריך, תופיע הודעה ב-Slack.

המאמרים הבאים

דוגמאות נוספות להתראות פרוגרמטיות, שיעזרו לכם ללמוד איך מבצעים את הפעולות הבאות: