Send a Slack message using the Google Cloud Functions (2nd gen)

Karthik Guttapudi
4 min readFeb 14, 2022

--

In this article we will see how to use the 2nd generation of the Google Cloud Functions to send a Slack message whenever a VM instance is created.

Slack

Let’s get started by setting up the Slack app, visit this link https://api.slack.com/apps to create an app

Click on Create new App, select from scratch, give it a name and choose the workspace and create it.

In created application, select the Incoming Webhooks, add a new webhook and choose the channel to which you want to send messages from Cloud Functions.

Cloud Functions

Create a Cloud Function, select the 2nd gen as Environment and give it a name. Click on the ADD EVENTARC TRIGGER button, select Compute Engine as the Event provider and beta.compute.instances.insert as Event.

Note: Grant permissions to the service account to receive events via Cloud Audit Logs ( the GRANT button below the service account drop-down), and save the trigger.

Under the Runtime, build and connection settings section, leave the defaults and add a Runtime Environment variable “SLACK_URL”, value would be the Webhook URL that we added earlier.

Click Next, select “Node.js 16” as the runtime. We will be using the needle library to make the post call to slack URL, add it to dependencies in package.json.

Replace the code in index.js with the below code. Here we are are building the message and making a post call to the Webhook URL to send this message to the Slack channel.

const functions = require(‘@google-cloud/functions-framework’);
const needle = require(‘needle’);
const slackURL = process.env.SLACK_URL;// Register a CloudEvent callback with the Functions Framework that will// be triggered by an Eventarc Cloud Audit Logging trigger.//// Note: this is NOT designed for second-party (Cloud Audit Logs -> Pub/Sub) triggers!functions.cloudEvent(‘helloAuditLog’, cloudEvent => {let data = cloudEvent.data;if(!data.operation.last){console.log(‘operation is not last, skipping event’);return;}// Print out details from the CloudEvent itselfconsole.log(‘Event type:’, cloudEvent.type);// Print out the CloudEvent’s `subject` property// See https://github.com/cloudevents/spec/blob/v1.0.1/spec.md#subjectconsole.log(‘Subject:’, cloudEvent.subject);// Print out details from the `protoPayload`// This field encapsulates a Cloud Audit Logging entry// See https://cloud.google.com/logging/docs/audit#audit_log_entry_structureconst payload = data.protoPayload;if (payload) {console.log(‘API method:’, payload.methodName);console.log(‘Resource name:’, payload.resourceName);console.log(‘Principal:’, payload.authenticationInfo.principalEmail);const resourceNameParts = payload.resourceName.split(‘/’);const data = { ‘text’: `A vm instance — \’${resourceNameParts[5]}\’ was created by user ${payload.authenticationInfo.principalEmail}`};needle(‘post’, slackURL, data, {json: true}).then((res) => {console.log(`Status: ${res.statusCode}`);console.log(‘Body: ‘, res.body);}).catch((err) => {console.error(err);});}

Click on Deploy and wait for the function to be ready.

Testing

Our Cloud Function should be triggered whenever a VM instance is created. In the Compute Engine, create a VM instance, give it a name and select region us-central1 and create.

By default, all the admin activities like VM instance creation etc are captured in the logs, after we create our instance we can view the audit logs in the Logs Explorer service.

As we can see, there are two log entries related to our VM instance creation, to avoid our function from being called twice we used this condition in our index.js

As soon as our VM instance gets created, our Cloud Function sends a Slack message to the channel,

Conclusion

That’s it ! we have seen how to use the second generation of Google Cloud Functions, there are lot of new features please check this link for more details — https://cloud.google.com/functions/docs/2nd-gen/overview

--

--