This tutorial demonstrates how to write and trigger an event-driven Cloud Run function with a Pub/Sub trigger.
You can configure the routing of events, including the event source and the event target, by specifying filters for an Eventarc trigger. For the example in this tutorial, publishing a message to a Pub/Sub topic triggers the event, and a request is sent to your function in the form of an HTTP request.
If you are new to Pub/Sub and want to learn more, see the Pub/Sub documentation for quickstarts and key references.
Objectives
In this tutorial, you will:
Costs
In this document, you use the following billable components of Google Cloud:
To generate a cost estimate based on your projected usage,
use the pricing calculator.
Before you begin
Security constraints defined by your organization might prevent you from completing the following steps. For troubleshooting information, see Develop applications in a constrained Google Cloud environment.
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
- If you are not using Cloud Shell, update the Google Cloud CLI
components and log in using your account:
gcloud components update gcloud auth login
- Enable the APIs:
gcloud services enable artifactregistry.googleapis.com \ cloudbuild.googleapis.com \ eventarc.googleapis.com \ run.googleapis.com \ logging.googleapis.com \ pubsub.googleapis.com
- Set the configuration variables used in this tutorial:
export REGION=us-central1 gcloud config set run/region ${REGION} gcloud config set run/platform managed gcloud config set eventarc/location ${REGION}
- Create a service account:
SERVICE_ACCOUNT=eventarc-trigger-sa gcloud iam service-accounts create $SERVICE_ACCOUNT
If you are under a domain restriction organization policy restricting unauthenticated invocations for your project, you will need to access your deployed service as described under Testing private services.
Required roles
-
If you are the project creator, you are granted the basic Owner role (
roles/owner
). By default, this Identity and Access Management (IAM) role includes the permissions necessary for full access to most Google Cloud resources and you can skip this step.If you are not the project creator, required permissions must be granted on the project to the appropriate principal. For example, a principal can be a Google Account (for end users) or a service account (for applications and compute workloads). For more information, see the Roles and permissions page for your event destination.
Required permissions
To get the permissions that you need to complete this tutorial, ask your administrator to grant you the following IAM roles on your project:
-
Cloud Run Source Developer (
roles/run.sourceDeveloper
) -
Project IAM Admin (
roles/resourcemanager.projectIamAdmin
) -
Service Account User (
roles/iam.serviceAccountUser
) -
Service Usage Admin (
roles/serviceusage.serviceUsageAdmin
) -
Logs View Accessor (
roles/logging.viewAccessor
)
For more information about granting roles, see Manage access to projects, folders, and organizations.
You might also be able to get the required permissions through custom roles or other predefined roles.
-
Cloud Run Source Developer (
Make note of the Compute Engine default service account as you will you attach it to an Eventarc trigger to represent the identity of the trigger for testing purposes. This service account is automatically created after enabling or using a Google Cloud service that uses Compute Engine, and with the following email format:
PROJECT_NUMBER-compute@developer.gserviceaccount.com
Replace
PROJECT_NUMBER
with your Google Cloud project number. You can find your project number on the Welcome page of the Google Cloud console or by running the following command:gcloud projects describe PROJECT_ID --format='value(projectNumber)'
For production environments, we strongly recommend creating a new service account and granting it one or more IAM roles that contain the minimum permissions required and follow the principle of least privilege.
- By default, Cloud Run services are only callable by Project
Owners, Project Editors, and Cloud Run Admins and Invokers.
You can
control
access on a per-service basis; however, for testing purposes, grant the
Cloud Run
Invoker role (
run.invoker
) on the Google Cloud project to the Compute Engine service account. This grants the role on all Cloud Run services and jobs in a project.gcloud projects add-iam-policy-binding PROJECT_ID \ --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \ --role=roles/run.invoker
Note that if you create a trigger for an authenticated Cloud Run service without granting the Cloud Run Invoker role, the trigger is created successfully and is active. However, the trigger will not work as expected and a message similar to the following appears in the logs:
The request was not authenticated. Either allow unauthenticated invocations or set the proper Authorization header.
- Grant the
Eventarc
Event Receiver role (
roles/eventarc.eventReceiver
) on the project to the Compute Engine default service account so that the Eventarc trigger can receive events from event providers.gcloud projects add-iam-policy-binding PROJECT_ID \ --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \ --role=roles/eventarc.eventReceiver
- Before creating a trigger for direct events from Cloud Storage,
grant the Pub/Sub
Publisher role (
roles/pubsub.publisher
) to the Cloud Storage service agent:SERVICE_ACCOUNT="$(gcloud storage service-agent --project=PROJECT_ID)" gcloud projects add-iam-policy-binding PROJECT_ID \ --member="serviceAccount:${SERVICE_ACCOUNT}" \ --role='roles/pubsub.publisher'
- If you enabled the Cloud Pub/Sub service agent on or before April
8, 2021, to support authenticated Pub/Sub push requests, grant
the Service
Account Token Creator role (
roles/iam.serviceAccountTokenCreator
) to the service agent. Otherwise, this role is granted by default:gcloud projects add-iam-policy-binding PROJECT_ID \ --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-pubsub.iam.gserviceaccount.com \ --role=roles/iam.serviceAccountTokenCreator
Create a Pub/Sub topic
In Cloud Run functions, Pub/Sub topics are not automatically created when you deploy a function. Before deploying your function, publish a message to this Pub/Sub topic to trigger the function:
gcloud pubsub topics create YOUR_TOPIC_NAME
Prepare the application
Clone the sample app repository to your local machine:
Node.js
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git
Python
git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
Go
git clone https://github.com/GoogleCloudPlatform/golang-samples.git
Java
git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
.NET
git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git
Ruby
git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git
PHP
git clone https://github.com/GoogleCloudPlatform/php-docs-samples.git
Change to the directory that contains the Cloud Run functions sample code for accessing Pub/Sub:
Node.js
cd nodejs-docs-samples/functions/v2/helloPubSub/
Python
cd python-docs-samples/functions/v2/pubsub/
Go
cd golang-samples/functions/functionsv2/hellopubsub/
Java
cd java-docs-samples/functions/v2/pubsub/
.NET
cd dotnet-docs-samples/functions/helloworld/HelloPubSub/
Ruby
cd ruby-docs-samples/functions/helloworld/pubsub/
PHP
cd php-docs-samples/functions/helloworld_pubsub/
Take a look at the sample code:
Node.js
Python
Go
Java
.NET
Ruby
PHP
Deploy an event-driven function
To deploy the function, run the following command in the directory that contains the sample code:
Node.js
gcloud beta run deploy FUNCTION \
--source . \
--function helloPubSub \
--base-image nodejs22 \
Python
gcloud beta run deploy FUNCTION \
--source . \
--function subscribe \
--base-image python312 \
Go
gcloud beta run deploy FUNCTION \
--source . \
--function HelloPubSub \
--base-image go122 \
Java
gcloud beta run deploy FUNCTION \
--source . \
--function functions.SubscribeToTopic \
--base-image java21 \
.NET
gcloud beta run deploy FUNCTION \
--source . \
--function HelloPubSub.Function \
--base-image dotnet8 \
Ruby
gcloud beta run deploy FUNCTION \
--source . \
--function hello_pubsub \
--base-image ruby33 \
PHP
gcloud beta run deploy FUNCTION \
--source . \
--function helloworldPubsub \
--base-image php83 \
Replace FUNCTION with the name of the function you are deploying. If you omit this parameter, you will be prompted to enter a name when you run the command.
BASE_IMAGE is the base image environment for your function. For more details about base images and the packages included in each image, see Runtimes base images.
If you are prompted to create a repository in the specified region, respond by
pressing y
.
When the deployment is complete, the Google Cloud CLI displays a URL where
the service is running.
Create an Eventarc trigger
To deploy the function with a Pub/Sub trigger, run the following command in the directory that contains the sample code:
Create an Eventarc Pub/Sub trigger:
gcloud eventarc triggers create TRIGGER_NAME \ --location=${REGION} \ --destination-run-service=FUNCTION \ --destination-run-region=${REGION} \ --event-filters="type=google.cloud.pubsub.topic.v1.messagePublished" \ --service-account=PROJECT_NUMBER-compute@developer.gserviceaccount.com
Replace:
- TRIGGER_NAME with the name for your trigger.
- FUNCTION with the name of your function.
- PROJECT_NUMBER with your Google Cloud project number.
Note that when creating an Eventarc trigger for the first time in a Google Cloud project, there might be a delay in provisioning the Eventarc service agent. This issue can usually be resolved by attempting to create the trigger again. For more information, see Permission denied errors.
Confirm that the trigger was successfully created. Note that although your trigger is created immediately, it can take up to two minutes for a trigger to be fully functional.
gcloud eventarc triggers list --location=${REGION}
The output should be similar to the following:
NAME: helloworld-events TYPE: google.cloud.pubsub.topic.v1.messagePublished DESTINATION: Cloud Run service: helloworld-events ACTIVE: Yes LOCATION: us-central1
Trigger the function
To test the Pub/Sub function:
Assign the topic to a variable:
TOPIC_ID=$(gcloud eventarc triggers describe TRIGGER_NAME --location $REGION --format='value(transport.pubsub.topic)')
Publish a message to the topic:
gcloud pubsub topics publish $TOPIC_ID --message="Hello World"
The Cloud Run service logs the body of the incoming message. You can view this in the Logs section of your Cloud Run instance:
- Navigate to the Google Cloud console.
- Click the function.
Select the Logs tab.
Logs might take a few moments to appear. If you don't see them immediately, check again after a few moments.
Look for the "Hello World!" message.
Clean up
If you created a new project for this tutorial, delete the project. If you used an existing project and want to keep it without the changes added in this tutorial, delete the resources created for the tutorial.
Delete the project
The easiest way to eliminate billing is to delete the project that you created for the tutorial.
To delete the project:
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
Delete tutorial resources
Delete the Cloud Run service you deployed in this tutorial:
gcloud run services delete SERVICE_NAME
Where
SERVICE_NAME
is your chosen service name.You can also delete Cloud Run services from the Google Cloud console.
Remove any gcloud CLI default configurations you added during the tutorial setup.
For example:
gcloud config unset run/region
or
gcloud config unset project
Delete other Google Cloud resources created in this tutorial:
- Delete the Eventarc trigger:
gcloud eventarc triggers delete TRIGGER_NAME
ReplaceTRIGGER_NAME
with the name of your trigger.
- Delete the Eventarc trigger: