Stay organized with collections Save and categorize content based on your preferences.
This tutorial shows you how to deploy an event-driven function in Cloud Run, and use Eventarc to trigger the function in response to Cloud Storage events using the Google Cloud CLI.
By specifying filters for an Eventarc trigger, you can configure the routing of events, including the event source and the event target. For the example in this tutorial, an update to a Cloud Storage bucket triggers the event, and a request is sent to your function in the form of an of HTTP request.
ObjectivesIn this tutorial, you will:
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.
New Google Cloud users might be eligible for a
free trial.
Before you beginSecurity 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.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
To initialize the gcloud CLI, run the following command:
gcloud init
Create or select a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the 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.
Verify that billing is enabled for your Google Cloud project.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
To initialize the gcloud CLI, run the following command:
gcloud init
Create or select a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the 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.
Verify that billing is enabled for your Google Cloud project.
gcloud components update gcloud auth login
gcloud services enable artifactregistry.googleapis.com \ cloudbuild.googleapis.com \ eventarc.googleapis.com \ run.googleapis.com \ storage.googleapis.com
export REGION=us-central1 gcloud config set run/region ${REGION} gcloud config set run/platform managed gcloud config set eventarc/location ${REGION}
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.
You or your administrator must grant the deployer account, the trigger identity, and optionally, the Pub/Sub service agent and the Cloud Storage service agent the following IAM roles.
Required roles for the deployer accountIf 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.
To get the permissions that you need to complete this tutorial, ask your administrator to grant you the following IAM roles on your project:
roles/cloudbuild.builds.editor
)roles/run.admin
)roles/run.sourceDeveloper
)roles/eventarc.admin
)roles/logging.viewAccessor
)roles/resourcemanager.projectIamAdmin
)roles/iam.serviceAccountAdmin
)roles/iam.serviceAccountUser
)roles/serviceusage.serviceUsageAdmin
)roles/storage.admin
)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.
Note that by default, Cloud Build permissions include permissions to upload and download Artifact Registry artifacts.
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.
Note:The iam.automaticIamGrantsForDefaultServiceAccounts
organization policy constraint prevents the Editor role from being automatically granted to default service accounts. If you created your organization after May 3, 2024, this constraint is enforced by default.
We strongly recommend that you enforce this constraint to disable the automatic role grant. If you disable the automatic role grant, you must decide which roles to grant to the default service accounts, and then grant these roles yourself.
If the default service account already has the Editor role, we recommend that you replace the Editor role with less permissive roles.To safely modify the service account's roles, use Policy Simulator to see the impact of the change, and then grant and revoke the appropriate roles.
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.
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
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'
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 Cloud Storage bucket to use as the event source:
gcloud storage buckets create -l us-central1 gs://PROJECT_ID-bucket/Note: The Cloud Storage bucket must reside in the same Google Cloud project and region or multi-region as the Eventarc trigger. Write an event-driven function
To write an event-driven function, follow these steps:
Node.jsCreate a new directory named helloGCS
and change directory into it:
mkdir helloGCS
cd helloGCS
Create a package.json
file in the helloGCS
directory to specify Node.js dependencies:
Create an index.js
file in the helloGCS
directory with the following Node.js sample:
Create a new directory named helloGCS
and change directory into it:
mkdir helloGCS
cd helloGCS
Create a requirements.txt
file in the helloGCS
directory, to specify Python dependencies:
This adds packages needed by the sample.
Create a main.py
file in the helloGCS
directory with the following Python sample:
Deploy the function named helloworld-events
by running the following command in the directory that contains the sample code:
gcloud run deploy helloworld-events \
--source . \
--function helloGCS \
--base-image BASE_IMAGE \
--region us-central1
Replace BASE_IMAGE with the base image environment for your function, for example, nodejs22
. For more details about base images and the packages included in each image, see Supported language runtimes and base images.
gcloud run deploy helloworld-events \
--source . \
--function hello_gcs \
--base-image BASE_IMAGE \
--region us-central1
Replace BASE_IMAGE with the base image environment for your function, for example, python313
. For more details about base images and the packages included in each image, see Supported language runtimes and base images.
When the deployment is complete, the Google Cloud CLI displays a URL where your service is running.
Create an Eventarc triggerThe Eventarc trigger sends events from the Cloud Storage bucket to your helloworld-events
Cloud Run service.
Create a trigger that filters Cloud Storage events:
gcloud eventarc triggers create TRIGGER_NAME \ --location=${REGION} \ --destination-run-service=helloworld-events \ --destination-run-region=${REGION} \ --event-filters="type=google.cloud.storage.object.v1.finalized" \ --event-filters="bucket=PROJECT_ID-bucket" \ --service-account=PROJECT_NUMBER-compute@developer.gserviceaccount.com
Replace:
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.storage.object.v1.finalized
DESTINATION: Cloud Run service: helloworld-events
ACTIVE: Yes
LOCATION: us-central1
Upload a text file to the Cloud Storage bucket to generate an event which is routed to the function. The Cloud Run function logs the event in the service logs.
Upload a text file to Cloud Storage, to generate an event:
echo "Hello World" > random.txt gcloud storage cp random.txt gs://PROJECT_ID-bucket/random.txt
The upload generates an event and the Cloud Run function logs the event's message.
To view the log entry:
Filter the log entries and return the output in JSON format:
gcloud logging read "resource.labels.service_name=helloworld-events AND textPayload:random.txt" --format=json
Look for a log entry similar to:
[ { .... "resource": { "labels": { .... "location": "us-central1", ..... "service_name": "helloworld-events" }, }, "textPayload": "File: random.txt", ..... } ]Note: If you don't see a log entry, wait a few minutes and retry the
gcloud logging read
command. The trigger can take up to two minutes after being created to start filtering events.
Logs might take a few moments to appear. If you don't see them immediately, check again after a minute.
After you see the log entry, this confirms that you have successfully deployed an event-driven function that was triggered when a text file was uploaded to Cloud Storage.
Success: You deployed an event-driven function in Cloud Run and used Eventarc to trigger the function in response to Cloud Storage events. Clean upIf 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 projectThe easiest way to eliminate billing is to delete the project that you created for the tutorial.
To delete the project:
appspot.com
URL, delete selected resources inside the project instead of deleting the whole project.If you plan to explore multiple architectures, tutorials, or quickstarts, reusing projects can help you avoid exceeding project quota limits.
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:
gcloud eventarc triggers delete TRIGGER_NAMEReplace
TRIGGER_NAME
with the name of your trigger.Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-08-07 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-07 UTC."],[],[]]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4