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 experience, from setup to confirmation.
Learning Objectives
Successfully complete this lab by achieving the following learning objectives:
- Enable required APIs.
- Use the API Library to find and enable the Cloud Pub/Sub API.
- Use the API Library to find and enable the Cloud Functions API.
- Use the API Library to find and enable the Cloud Build API.
- Create Pub/Sub topic.
- From the main console navigation, go to Cloud Pub/Sub.
- Click Create a topic.
- In the dialog, enter a name greetings for the topic.
- Click Create.
- Create a Cloud Function.
- From the main console, go to Cloud Functions.
- Click Create function.
- Configure the function with the following values:
- Name: la-pubsub-function
- Trigger: Cloud Pub/Sub
- Topic: greetings
- Source code: Inline editor
- Runtime: Python 3.7
- In the main.py field, enter the following code:
import base64 def greetings_pubsub(data, context): if 'data' in data: name = base64.b64decode(data['data']).decode('utf-8') else: name = 'folks' print('Greetings {} from Linux Academy!'.format(name))
- Set Function to Execute to greetings_pubsub.
- Click Create.
- Publish message to topic from console.
- Click the newly created Cloud Function name.
- Switch to Trigger.
- Click the topic link to go to the Cloud Pub/Sub topic.
- From the Topic page, click Publish Message.
- In the Message field, enter everyone around the world.
- Click Publish.
- Confirm Cloud Function execution.
- Return to the Cloud Functions dashboard.
- Click the Cloud Function’s name.
- From the Cloud Function navigation, click View Logs.
- Locate the most recent log.
- Confirm function execution.
- Trigger Cloud Function directly from command line.
Click Activate Cloud Shell from the top row of the console.
In the Cloud Shell, enter the following code:
DATA=$(printf 'my friends' | base64) gcloud functions call la-pubsub-function --data '{"data":"'$DATA'"}'
After a moment, refresh the logs page and confirm the Cloud Function execution.
- Publish message to topic from command line.
In the Cloud Shell, enter the following command:
gcloud pubsub topics publish greetings --message "y'all"
After a moment, refresh the log page to confirm the function has executed.