Cloud Functions can be triggered in two ways: through a direct HTTP request or through a background event. One of the most frequently used services for background events is Cloud Pub/Sub, Google Cloud’s platform-wide messaging service. In this pairing, Cloud Functions becomes a direct subscriber to a specific Cloud Pub/Sub topic, which allows code to be run whenever a message is received on a specific topic. In this hands-on lab, we’ll walk through the entire process from deploying the function to testing it by publishing messages to Pub/Sub.
Learning Objectives
Successfully complete this lab by achieving the following learning objectives:
- Enable APIs
- Inside the GCP console, click the Activate Cloud Shell icon.
- When the terminal is ready, enable the following necessary APIs: cloudbuild.googleapis.com, cloudfunctions.googleapis.com, and pubsub.googleapis.com.
- Create the Pub/Sub Topic
- From the GCP menu, select Pub/Sub in the Big Data section.
- Click Create Topic.
- Enter "greetings" in the Topic ID, and click Create Topic.
- Create the Cloud Function
- From the GCP menu, select Cloud Functions in the Compute section. Then click Create Function.
- Under Basics, change the function name to "greetings".
- Under Trigger, change the trigger type to Cloud Pub/Sub, and choose the topic you just created.
- Click Save. Then click Next.
- Change the Runtime to Python 3.7 and set the Entry Point to "greetings".
Enter the following code into the editor:
import base64 def greetings(data, context): if 'data' in data: name = base64.b64decode(data['data']).decode('utf-8') else: name = 'folks' print('Hello {} from Cloud Functions!'.format(name))
- Click Deploy.
- Publish Messages to Test the Function
- From the GCP menu, select Pub/Sub in the Big Data section.
- Select the greetings topic and click Publish Message.
- Under Message Body, enter the text "Cloud Gurus".
- Click Publish.
- Go back to Cloud Functions (in the Compute section of the GCP menu), and select the greetings function.
- Click the Logs tab and look in the logs for the function. You should see the message: "Hello Cloud Gurus from Cloud Functions!"
- Now publish a message from the Cloud Shell terminal. After a few minutes, the logs should refresh to show the message "Hello Everyone from Cloud Functions!"
- You can also trigger the function directly with
gcloud
, once you have created a base64 payload.