Use Eventarc to receive events from Cloud Storage


This tutorial shows you how to deploy a containerized application using an authenticated Cloud Run service that receives events through Eventarc.

By specifying filters for an Eventarc trigger, you can configure the routing of events, including the event source and the event target. In this case, an update to a Cloud Storage bucket triggers the event and a request is sent to your Cloud Run service in the form of an of HTTP request.

Objectives

In this tutorial, you will:

  1. Create a Cloud Storage bucket to be the event source.

  2. Deploy an event receiver service to Cloud Run that requires authenticated invocations.

  3. Create an Eventarc trigger that routes events from the Cloud Storage bucket to the Cloud Run service.

  4. Generate an event by uploading a file to the Cloud Storage bucket and view the event in the Cloud Run logs.

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 .

New Google Cloud users might be eligible for a free trial .

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 .

  1. 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.
  2. Install the Google Cloud CLI.

  3. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity .

  4. To initialize the gcloud CLI, run the following command:

    gcloud  
    init
  5. 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.

  6. Verify that billing is enabled for your Google Cloud project .

  7. Install the Google Cloud CLI.

  8. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity .

  9. To initialize the gcloud CLI, run the following command:

    gcloud  
    init
  10. 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.

  11. Verify that billing is enabled for your Google Cloud project .

  12. 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
  13. Enable the APIs:
    gcloud  
    services  
     enable 
      
    artifactregistry.googleapis.com  
     \ 
      
    cloudbuild.googleapis.com  
     \ 
      
    eventarc.googleapis.com  
     \ 
      
    run.googleapis.com  
     \ 
      
    storage.googleapis.com
  14. 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 
     } 
    
  15. You or your administrator must grant the deployer account, the trigger identity, and optionally, the Pub/Sub service agent the following IAM roles.

    Required roles for the trigger identity

    1. 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 .

    2. 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.
    3. 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

    Optional role for the Pub/Sub service agent

    • 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 an Artifact Registry standard repository

Create an Artifact Registry standard repository to store your container image:

gcloud  
artifacts  
repositories  
create  
 REPOSITORY 
  
 \ 
  
--repository-format = 
docker  
 \ 
  
--location = 
 $REGION 

Replace REPOSITORY with a unique name for the repository.

Create a Cloud Storage bucket

Create a Cloud Storage bucket to use as the event source:

gcloud  
storage  
buckets  
create  
gs:// PROJECT_ID 
-bucket/  
--location = 
us-central1

After the event source is created, you can deploy the event receiver service on Cloud Run.

Deploy an event receiver to Cloud Run

Deploy a Cloud Run service that receives and logs events.

  1. Clone the GitHub repository:

    Node.js

    git  
    clone  
    https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

    Python

    git  
    clone  
    https://github.com/GoogleCloudPlatform/python-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

    Go

    git  
    clone  
    https://github.com/GoogleCloudPlatform/golang-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

    Java

    git  
    clone  
    https://github.com/GoogleCloudPlatform/java-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

    C#

    git  
    clone  
    https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

  2. Change to the directory that contains the Cloud Run sample code:

    Node.js

     cd 
      
    nodejs-docs-samples/eventarc/audit-storage/

    Python

     cd 
      
    python-docs-samples/eventarc/audit-storage/

    Go

     cd 
      
    golang-samples/eventarc/audit_storage/

    Java

     cd 
      
    java-docs-samples/eventarc/audit-storage/

    C#

     cd 
      
    dotnet-docs-samples/eventarc/audit-storage/
  3. Build the container for the Cloud Run service:

     export 
      
     PROJECT_ID 
     = 
     $( 
    gcloud  
    config  
    get-value  
    project ) 
     export 
      
     SERVICE_NAME 
     = 
    helloworld-events
    gcloud  
    builds  
    submit  
    --tag  
     $REGION 
    -docker.pkg.dev/ ${ 
     PROJECT_ID 
     } 
    / REPOSITORY 
    / ${ 
     SERVICE_NAME 
     } 
    :v1
  4. Deploy the container image to Cloud Run:

    gcloud  
    run  
    deploy  
     ${ 
     SERVICE_NAME 
     } 
      
     \ 
      
    --image  
     $REGION 
    -docker.pkg.dev/ ${ 
     PROJECT_ID 
     } 
    / REPOSITORY 
    / ${ 
     SERVICE_NAME 
     } 
    :v1
  5. At the Allow public access to helloworld-events (y/N)? prompt, respond n for "No".

When you see the Cloud Run service URL, the deployment is complete.

Create an Eventarc trigger

The Eventarc trigger sends events from the Cloud Storage bucket to the helloworld-events Cloud Run service. The service requires authentication, and the event should be triggered by a caller that has a service account with the required IAM roles and permissions to use the resource.

  1. Create a trigger that filters Cloud Storage events:

    gcloud  
    eventarc  
    triggers  
    create  
     ${ 
     SERVICE_NAME 
     } 
      
     \ 
      
    --destination-run-service = 
     ${ 
     SERVICE_NAME 
     } 
      
     \ 
      
    --destination-run-region = 
     ${ 
     REGION 
     } 
      
     \ 
      
    --location = 
     ${ 
     REGION 
     } 
      
     \ 
      
    --event-filters = 
     "type=google.cloud.storage.object.v1.finalized" 
      
     \ 
      
    --event-filters = 
     "bucket= PROJECT_ID 
    -bucket" 
      
     \ 
      
    --service-account = 
     PROJECT_NUMBER 
    -compute@developer.gserviceaccount.com

    This creates a trigger called helloworld-events .

    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 .

  2. 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 
    

Generate and view an event

Upload a text file to the Cloud Storage bucket to generate an event which is routed to the Cloud Run service. The Cloud Run service logs the event in the service logs.

  1. To generate an event:

    Upload a text file to Cloud Storage:

    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 service logs the event's message.

  2. To view the log entry:

    1. 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
    2. Look for a log entry similar to:

      "textPayload": "Detected change in Cloud Storage bucket: objects/random.txt"

Logs might take a few moments to appear. If you don't see them immediately, check again after a minute.

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:

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete .
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

Delete tutorial resources

  1. 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 .

  2. Remove any gcloud CLI default configurations you added during the tutorial setup.

    For example:

    gcloud config unset run/region

    or

    gcloud config unset project

  3. Delete other Google Cloud resources created in this tutorial:

    • Delete the Eventarc trigger:
      gcloud eventarc triggers delete TRIGGER_NAME 
      
      Replace TRIGGER_NAME with the name of your trigger.

What's next

Create a Mobile Website
View Site in Mobile | Classic
Share by: