This guide covers the instructions for creating triggers for Cloud Run services and functions from Firestore events.
You can configure your Cloud Run services to be triggered by events in a Firestore database. When triggered, your service reads and updates a Firestore database in response to these events through the Firestore APIs and client libraries.
In a typical lifecycle, the following happens when a Cloud Run service is triggered by Firestore events:
The service waits for changes to a particular document.
When a change occurs, the service is triggered and performs its tasks.
The service receives a data object with a snapshot of the affected document. For
write
orupdate
events, the data object contains snapshots representing document state before and after the triggering event.
Event types
Firestore supports create
, update
, delete
, and write
events. The
write
event encompasses all modifications to a document.
Event type | Trigger |
---|---|
google.cloud.firestore.document.v1.created (default) |
Triggered when a document is written to for the first time. |
google.cloud.firestore.document.v1.updated |
Triggered when a document already exists and has any value changed. |
google.cloud.firestore.document.v1.deleted |
Triggered when a document with data is deleted. |
google.cloud.firestore.document.v1.written |
Triggered when a document is created, updated or deleted. |
Wildcards are written in triggers using curly braces, for example:
projects/YOUR_PROJECT_ID/databases/(default)/documents/collection/{document_wildcard}
Specify the document path
To trigger your service, specify a document path to listen to. The document path must be in the same Google Cloud project as the service.
Here are a few examples of valid document paths:
users/marie
: valid trigger. Monitors a single document,/users/marie
.users/{username}
: valid trigger. Monitors all user documents. Wildcards are used to monitor all documents in the collection.users/{username}/addresses
: invalid trigger. Refers to the subcollectionaddresses
, not a document.users/{username}/addresses/home
: valid trigger. Monitors the home address document for all users.users/{username}/addresses/{addressId}
: valid trigger. Monitors all address documents.users/{user=**}
: valid trigger. Monitors all user documents and any documents in subcollections under each user document such as/users/userID/address/home
or/users/userID/phone/work
.
Wildcards and parameters
If you don't know the specific document you want to monitor, use a {wildcard}
instead of the document ID:
users/{username}
listens for changes to all user documents.
In this example, when any field on any document in users
is changed, it
matches a wildcard called {username}
.
If a document in users
has
subcollections, and a
field in one of those subcollections' documents is changed, the {username}
wildcard is not triggered. If your goal is to respond to events in
subcollections also, use the multi-segment wildcard {username=**}
.
Wildcard matches are extracted from document paths. You can define as many
wildcards as you like to substitute explicit collection or document IDs. You can
use up to one multi-segment wildcard like {username=**}
.
Event structures
This trigger invokes your service with an event similar to:
{ "oldValue": { // Update and Delete operations only A Document object containing a pre-operation document snapshot }, "updateMask": { // Update operations only A DocumentMask object that lists changed fields. }, "value": { // A Document object containing a post-operation document snapshot } }
Each Document
object contains one or more Value
objects. See the
Value
documentation
for type references.
Before you begin
- Make sure you have set up a new project for Cloud Run as described in the setup page.
Enable the Artifact Registry, Cloud Build, Cloud Run Admin API, Eventarc, Firestore Cloud Logging, and Pub/Sub APIs:
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.
Note that by default, Cloud Build permissions include permissions to upload and download Artifact Registry artifacts.
Required permissions
To get the permissions that you need to configure Firestore triggers, ask your administrator to grant you the following IAM roles on your project:
-
Cloud Build Editor (
roles/cloudbuild.builds.editor
) -
Cloud Run Admin (
roles/run.admin
) -
Datastore Owner (
roles/datastore.owner
) -
Eventarc Admin (
roles/eventarc.admin
) -
Logs View Accessor (
roles/logging.viewAccessor
) -
Project IAM Admin (
roles/resourcemanager.projectIamAdmin
) -
Service Account Admin (
roles/iam.serviceAccountAdmin
) -
Service Account User (
roles/iam.serviceAccountUser
) -
Service Usage Admin (
roles/serviceusage.serviceUsageAdmin
)
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 Build Editor (
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
- 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
Set up your Firestore database
Before you deploy your service, you must create a Firestore database:
Go to the Firestore Data page.
Select Create Database.
Click Native Mode, then select Continue.
In the Name your database field, enter a Database ID, such as
firestore-db
.In Location type, select Region and choose the region for where your database is to reside. This choice is permanent.
Leave the Secure rules section as is.
Click Create database.
The Firestore data model consists of collections that contain documents. A document contains a set of key-value pairs.
Create triggers
Depending on the type of service you are deploying, you can either:
Create a trigger for services
You can specify a trigger after you deploy a service.
Click the tab for instructions using the tool of your choice.
Console
Deploy your Cloud Run service using containers or from source.
In the Google Cloud console, go to Cloud Run:
From the list of services, click an existing service.
On the Service details page, navigate to the Triggers tab.
Click Add trigger, and select Firestore trigger.
In the Eventarc trigger pane, modify the trigger details as follows:
In the Trigger name filed, enter a name for the trigger, or use the default name.
Select a Trigger type from the list to specify one of the following trigger types:
Google Sources to specify triggers for Pub/Sub, Cloud Storage, Firestore, and other Google event providers.
Third-party to integrate with non-Google providers that offer an Eventarc source. For more information, see Third-party events in Eventarc.
Select Firestore from the Event provider list, to select a product that provides the type of event for triggering your service. For the list of event providers, see Event providers and destinations.
Select type=google.cloud.firestore.document.v1.created from the Event type list. Your trigger configuration varies depending on the supported event type. For more information, see Event types.
In the Filters section, select a database, operation and attribute values, or use the default selections.
If the Region field is enabled, select a location for the Eventarc trigger. In general, the location of an Eventarc trigger should match the location of the Google Cloud resource that you want to monitor for events. In most scenarios, you should also deploy your service in the same region. See Understand Eventarc locations for more details about Eventarc trigger locations.
In the Service account field, select a service account. Eventarc triggers are linked to service accounts to use as an identity when invoking your service. Your Eventarc trigger's service account must have the permission to invoke your service. By default, Cloud Run uses the Compute Engine default service account.
Optionally, specify the Service URL path to send the incoming request to. This is the relative path on the destination service to which the events for the trigger should be sent. For example:
/
,/route
,route
, androute/subroute
.Once you've completed the required fields, click Save trigger.
After creating the trigger, verify its health by ensuring that there is a checkmark check_circle on the Triggers tab.
gcloud
Deploy your Cloud Run service using containers or from source.
Run the following command to create a trigger that filters events:
gcloud eventarc triggers create TRIGGER_NAME \ --location=EVENTARC_TRIGGER_LOCATION \ --destination-run-service=SERVICE \ --destination-run-region=REGION \ --event-filters="type=google.cloud.firestore.document.v1.created" \ --service-account=PROJECT_NUMBER-compute@developer.gserviceaccount.com
Replace:
TRIGGER_NAME with the name for your trigger.
EVENTARC_TRIGGER_LOCATION with the location for the Eventarc trigger. In general, the location of an Eventarc trigger should match the location of the Google Cloud resource that you want to monitor for events. In most scenarios, you should also deploy your service in the same region. For more information, see Eventarc locations.
SERVICE with the name of the service you are deploying.
REGION with the Cloud Run region of the service.
PROJECT_NUMBER with your Google Cloud project number. Eventarc triggers are linked to service accounts to use as an identity when invoking your service. Your Eventarc trigger's service account must have the permission to invoke your service. By default, Cloud Run uses the Default compute service account.
The
event-filters
flag specifies the event filters that the trigger monitors. An event that matches all theevent-filters
, filters triggers calls to your service. Each trigger must have a supported event type. You can't change the event filter type after creation. To change the event filter type, you must create a new trigger and delete the old one. Optionally, you can repeat the--event-filters
flag with a supported filter in the formATTRIBUTE=VALUE
to add more filters.
Create a trigger for functions
Click the tab for instructions using the tool of your choice.
Console
When you use the Google Cloud console to create a function, you can also add a trigger to your function. Follow these steps to create a trigger for your function:
In the Google Cloud console, go to Cloud Run:
Click Write a function, and enter the function details. For more information about configuring functions during deployment, see Deploy functions.
In the Trigger section, click Add trigger.
Select Firestore trigger.
In the Eventarc trigger pane, modify the trigger details as follows:
Enter a name for the trigger in the Trigger name field, or use the default name.
Select a Trigger type from the list to specify one of the following trigger types:
Google Sources to specify triggers for Pub/Sub, Cloud Storage, Firestore, and other Google event providers.
Third-party to integrate with non-Google providers that offer an Eventarc source. For more information, see Third-party events in Eventarc.
Select Firestore from the Event provider list, to select a product that provides the type of event for triggering your function. For the list of event providers, see Event providers and destinations.
Select type=google.cloud.firestore.document.v1.created from the Event type list. Your trigger configuration varies depending on the supported event type. For more information, see Event types.
In the Filters section, select a database, operation and attribute values, or use the default selections.
If the Region field is enabled, select a location for the Eventarc trigger. In general, the location of an Eventarc trigger should match the location of the Google Cloud resource that you want to monitor for events. In most scenarios, you should also deploy your function in the same region. See Understand Eventarc locations for more details about Eventarc trigger locations.
In the Service account field, select a service account. Eventarc triggers are linked to service accounts to use as an identity when invoking your function. Your Eventarc trigger's service account must have the permission to invoke your function. By default, Cloud Run uses the Compute Engine default service account.
Optionally, specify the Service URL path to send the incoming request to. This is the relative path on the destination service to which the events for the trigger should be sent. For example:
/
,/route
,route
, androute/subroute
.
Once you've completed the required fields, click Save trigger.
gcloud
When you create a function using the gcloud CLI, you must first deploy your function, and then create a trigger. Follow these steps to create a trigger for your function:
Run the following command in the directory that contains the sample code to deploy your function:
gcloud beta run deploy FUNCTION \ --source . \ --function FUNCTION_ENTRYPOINT \ --base-image BASE_IMAGE_ID \ --region REGION
Replace:
FUNCTION with the name of the function you are deploying. You can omit this parameter entirely, but you will be prompted for the name if you omit it.
FUNCTION_ENTRYPOINT with the entry point to your function in your source code. This is the code Cloud Run executes when your function runs. The value of this flag must be a function name or fully-qualified class name that exists in your source code.
BASE_IMAGE_ID with the base image environment for your function. For more details about base images and the packages included in each image, see Runtimes base images.
REGION with the Google Cloud region where you want to deploy your function. For example,
us-central1
.
Run the following command to create a trigger that filters events:
gcloud eventarc triggers create TRIGGER_NAME \ --location=EVENTARC_TRIGGER_LOCATION \ --destination-run-service=FUNCTION \ --destination-run-region=REGION \ --event-filters="type=google.cloud.firestore.document.v1.created" \ --service-account=PROJECT_NUMBER-compute@developer.gserviceaccount.com
Replace:
TRIGGER_NAME with the name for your trigger.
EVENTARC_TRIGGER_LOCATION with the location for the Eventarc trigger. In general, the location of an Eventarc trigger should match the location of the Google Cloud resource that you want to monitor for events. In most scenarios, you should also deploy your function in the same region. For more information, see Eventarc locations.
FUNCTION with the name of the function you are deploying.
REGION with the Cloud Run region of the function.
PROJECT_NUMBER with your Google Cloud project number. Eventarc triggers are linked to service accounts to use as an identity when invoking your function. Your Eventarc trigger's service account must have the permission to invoke your function. By default, Cloud Run uses the Default compute service account.
The
event-filters
flag specifies the event filters that the trigger monitors. An event that matches all theevent-filters
, filters triggers calls to your function. Each trigger must have a supported event type. You can't change the event filter type after creation. To change the event filter type, you must create a new trigger and delete the old one. Optionally, you can repeat the--event-filters
flag with a supported filter in the formATTRIBUTE=VALUE
to add more filters.
What's next
- See examples of functions that are triggered when you make changes to a document inside of a specified collection.