Listen to your Pub/Sub notifications

Example reference architecture

Diagram of an example using budget alert programmatic notifications
            to automate a cost control response.
Figure 1: An example of using budget alerts to automate cost control responses using Pub/Sub for programmatic notifications and Cloud Run functions to automate a response.

This document explains how to listen to your programmatic budget notifications by subscribing to your Pub/Sub topic with Cloud Run function triggers. Without a subscriber, Pub/Sub drops published messages and you can't retrieve them later. In this document, you'll learn how to complete the following tasks:

  1. Create a Cloud Run function that listens to notifications.
  2. View Cloud Run function events.
  3. Test a Cloud Run function.

Before you begin

Before you begin, you must complete the following tasks:

  1. Create a budget
  2. Set up programmatic notifications

Create a Cloud Run function

To create a Cloud Run function, complete the following steps:

  1. In the Google Cloud console, go to the Cloud Run functions page.

    Go to Cloud Run functions

  2. Click CREATE FUNCTION and enter a Function name that's meaningful to your budget notification.

  3. Select the region where your Cloud Run functions will run. You can't edit this setting after you deploy your function.

  4. For Trigger type, select Cloud Pub/Sub.

  5. Select the Cloud Pub/Sub topic that you configured on your budget.

  6. Edit the Runtime, build, connections, and security settings as needed, then click Next.

  7. Write code using the inline editor or upload a file that tells your function how to handle notifications.

    See the following examples for code samples:

    For details about the notifications your code will receive, see Notification format.

  8. Set Entry point to the correct function to execute:

  9. Click DEPLOY.

View Cloud Run function events

After you deploy the Cloud Run function, click LOGS to view the logs from your function invocations.

Test a Cloud Run function

As notifications are sent to Pub/Sub, subscribers receive the messages. To test a sample notification and ensure that your function is working as expected, publish a message in Pub/Sub with the following object as the message body:

{
    "budgetDisplayName": "name-of-budget",
    "alertThresholdExceeded": 1.0,
    "costAmount": 100.01,
    "costIntervalStart": "2019-01-01T00:00:00Z",
    "budgetAmount": 100.00,
    "budgetAmountType": "SPECIFIED_AMOUNT",
    "currencyCode": "USD"
}

You can also add message attributes such as the billing account ID. For more information, see Notification format.

What's next

To learn more about how you can use programmatic notifications, review the following examples of programmatic cost control responses: