Configuring cluster upgrade notifications for third-party services

When you or Google Kubernetes Engine (GKE) initiates a cluster upgrade, you can receive notifications about these changes through third-party messaging services.

Services such as Slack offer incoming webhooks, a simple way to post messages from apps into Slack. Cloud Functions is a lightweight Compute Engine solution to create single-purpose, stand-alone functions that respond to Google Cloud events, such as notifications, without the need to manage a server or runtime environment. When a notification is sent, a trigger responds by executing an action, such as sending a Pub/Sub message.

There are many third-party services built with cross-application messaging functionality, such as SendGrid and IFTTT. You can use this tutorial as a template for connecting with such services.

This tutorial demonstrates how you can use Cloud Functions and Pub/Sub to send notifications about GKE cluster upgrades through Slack.

Objectives

  • Deploy a Slack application to receive external notifications from GKE.
  • Write a Cloud Function for sending Pub/Sub notifications to Slack.

Costs

This tutorial uses billable components of Google Cloud, including:

  • Cloud Functions
  • Pub/Sub
  • GKE

Use the Pricing Calculator to generate a cost estimate based on your projected usage.

Before you begin

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.

    Go to the project selector page

  3. Make sure that billing is enabled for your Cloud project. Learn how to confirm that billing is enabled for your project.

  4. Enable the Cloud Functions and Pub/Sub APIs.

    Enable the APIs

  5. Install and initialize the Cloud SDK.
  6. Update and install gcloud components:
    gcloud components update &&
    gcloud components install alpha beta
  7. Enable GKE upgrade notifications.

Slack notifications

The following sections walk you through how to set up Slack notifications.

Preparing the Slack application

  1. Download Slack for your computer. You also need to join a Slack workspace, either by registering with your email or by using an invitation sent by a Workspace Admin.

  2. Sign in to Slack using your workspace name and your Slack account credentials.

  3. Create a new Slack app:

    1. Choose the app's name and your Slack workspace. Click Create App.
    2. Under Features, click Incoming Webhooks.
    3. Enable Activate Incoming Webhooks.
    4. Click Add New Webhook to Workspace. An authorization page opens.
    5. From the drop-down menu, select the channel to which you would like notifications sent.
    6. Click Install.
    7. A webhook for your Slack application has been created. Copy the Webhook URL and save it for later use.

Writing the Cloud Function

Create a new directory named gke_slack and change directory into it:

mkdir ~/gke_slack
cd ~/gke_slack

Then, create files index.js and package.json in the gke_slack directory:

index.js

const { IncomingWebhook } = require('@slack/webhook');
const url = process.env.SLACK_WEBHOOK_URL;

const webhook = new IncomingWebhook(url);

// slackNotifier is the main function called by Cloud Functions
module.exports.slackNotifier = (pubSubEvent, context) => {
  const data = decode(pubSubEvent.data);

  // Send message to Slack.
  const message = createSlackMessage(data, pubSubEvent.attributes);
  webhook.send(message);
};

// decode decodes a pubsub event message from base64.
const decode = (data) => {
  return Buffer.from(data, 'base64').toString();
}

// createSlackMessage creates a message from a data object.
const createSlackMessage = (data, attributes) => {
  // Write the message data and attributes.
  text = `${data}`
  for (var key in attributes) {
    if (attributes.hasOwnProperty(key)) {
      text = text + `\n\t\`${key}: ${attributes[key]}\``
    }
  }
  const message = {
    text: text,
    mrkdwn: true,
  };
  return message;
}

SLACK_WEBHOOK_URL is a Cloud Functions environment variable specifying the webhook URL created for your Slack application. This environment variable will be defined when deploying the function.

This program uses Slack's webhook to listen for and receive messages from the Cloud Function. When an event is fired, a message is sent to the webhook then relayed to Slack.

The createSlackMessage function has been simplified for this example. You can expand the message to include much more, including text colors and images.

package.json

{
  "name": "gke-slack",
  "version": "0.0.1",
  "description": "Slack integration for GKE, using Cloud Functions",
  "main": "index.js",
  "dependencies": {
    "@slack/webhook": "5.0.1"
  }
}

package.json describes:

  • the program's name, version, and description
  • its primary runtime file(s)
  • its dependencies

This file is deceptively simple: you can add more dependencies, requirements, and other information as needed.

You should now have index.js and package.json in the gke_slack directory.

Deploying the Cloud Function

To deploy the subscribeSlack function with a Pub/Sub trigger, run the following command in the gke_slack directory:

gcloud functions deploy slackNotifier --trigger-topic topic-name \
  --runtime nodejs10 \
  --set-env-vars "SLACK_WEBHOOK_URL=https://hooks.slack.com/…"

Where:

  • SLACK_WEBHOOK_URL defines the webhook URL created for your Slack application. The URL format is: https://hooks.slack.com/services/T…/B…/….
  • topic-name is the name of the topic you specified when enabling GKE upgrade notifications.

You should see something like the following output:

Deploying function…
availableMemoryMb: 256
entryPoint: slackNotifier
environmentVariables:
  SLACK_WEBHOOK_URL: https://hooks.slack.com/services/…
eventTrigger:
  eventType: google.pubsub.topic.publish
  failurePolicy: {}
  resource: projects/[PROJECT-ID]/topics/[TOPIC-NAME]
  service: pubsub.googleapis.com
labels:
  deployment-tool: cli-gcloud
name: projects/[PROJECT-ID]/locations/us-central1/functions/slackNotifier
runtime: nodejs10
serviceAccountEmail: [PROJECT-ID]@appspot.gserviceaccount.com
sourceUploadUrl: https://storage.googleapis.com/…
status: ACTIVE
timeout: 60s
updateTime: 'YYYY-MM-DDThh:mm:ssZ'
versionId: '1'

After you've completed deployment of the Cloud Function, you will receive a Slack notification when GKE sends an upgrade notification.

Cleaning up

To avoid incurring charges to your Google Cloud Platform account for the resources used in this tutorial:

Deleting the project

The easiest way to eliminate billing is to delete the project that you created for the tutorial.

To delete the project:

  1. In the Cloud Console, go to the Manage resources page.

    Go to the Manage resources page

  2. In the project list, select the project that you want to delete and then click Delete .
  3. In the dialog, type the project ID and then click Shut down to delete the project.

Deleting the Cloud Function

Delete the Cloud Function you deployed in this tutorial:

gcloud functions delete slackNotifier

You can also delete Cloud Functions from the Google Cloud Console.

What's next