Receive direct events from Cloud Storage (gcloud CLI)

This quickstart shows you how to receive direct events from Cloud Storage (without using Cloud Audit Logs) in an unauthenticated Cloud Run service using Eventarc.

You can configure the triggering of notifications in response to various events inside a Cloud Storage bucket—object creation, deletion, archiving, and metadata updates. For more information, see Create a trigger to route Cloud Storage events to Cloud Run.

In this quickstart, you:

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

  2. Deploy an event receiver service to Cloud Run.

  3. Create an Eventarc trigger.

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

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. To initialize the gcloud CLI, run the following command:

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

  5. Make sure that billing is enabled for your Google Cloud project.

  6. Install the Google Cloud CLI.
  7. To initialize the gcloud CLI, run the following command:

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

  9. Make sure that billing is enabled for your Google Cloud project.

  10. Enable the Cloud Build, Cloud Run, Cloud Storage, Eventarc, and Pub/Sub APIs.

    gcloud services enable \
    cloudbuild.googleapis.com \
    eventarc.googleapis.com \
    pubsub.googleapis.com \
    run.googleapis.com \
    storage.googleapis.com
  11. Update gcloud components:
    gcloud components update
  12. Sign in using your account:
    gcloud auth login
  13. Set the configuration variables used in this quickstart:
    gcloud config set run/region us-central1
    gcloud config set run/platform managed
    gcloud config set eventarc/location us-central1
  14. 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:

    For more information about granting roles, see Manage access.

    You might also be able to get the required permissions through custom roles or other predefined roles.

  15. The Compute Engine default service account is automatically created after enabling or using a Google Cloud service that uses Compute Engine.

    For test purposes, you can attach this service account to an Eventarc trigger to represent the identity of the trigger. Note the email format to use when creating a trigger:

    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)'

    The Compute Engine service account is automatically granted the basic Editor role (roles/editor) on your project. However, if automatic role grants have been disabled, refer to the applicable Roles and permissions instructions on to create a new service account and grant it the required roles.

  16. 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
  17. 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, a Google-managed service account:

    SERVICE_ACCOUNT="$(gsutil kms serviceaccount -p PROJECT_ID)"
    
    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member="serviceAccount:${SERVICE_ACCOUNT}" \
        --role='roles/pubsub.publisher'
    
  18. 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 Google-managed service account. 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
  19. Download and install the Git source code management tool.

Create a Cloud Storage bucket

Create a Cloud Storage bucket to use as the event source:
gsutil mb -l us-central1 gs://PROJECT_ID-bucket/

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

Deploy the event receiver service to Cloud Run

Deploy a Cloud Run service that receives and logs events.

  1. Clone the repository and then change to the directory that contains the Cloud Run sample code:

    Go

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

    Java

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
    cd java-docs-samples/eventarc/audit-storage
    

    .NET

    git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git
    cd dotnet-docs-samples/eventarc/audit-storage
    

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git
    cd nodejs-docs-samples/eventarc/audit-storage
    

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
    cd python-docs-samples/eventarc/audit-storage
    
  2. Build the container and upload it to Cloud Build:

     gcloud builds submit --tag gcr.io/PROJECT_ID/helloworld-events
    
  3. Deploy the container image to Cloud Run:

     gcloud run deploy helloworld-events \
         --image gcr.io/PROJECT_ID/helloworld-events \
         --allow-unauthenticated
    

    When the deployment succeeds, the command line displays the service URL.

    Now that you have deployed a event receiver service called helloworld-events to Cloud Run, you can set up your trigger.

Create an Eventarc trigger

The Eventarc trigger sends events from the Cloud Storage bucket to the helloworld-events Cloud Run service.

  1. Create a trigger that filters Cloud Storage events and that uses the Compute Engine default service account.

     gcloud eventarc triggers create storage-events-trigger \
         --destination-run-service=helloworld-events \
         --destination-run-region=us-central1 \
         --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 storage-events-trigger.

    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. To confirm storage-events-trigger was successfully created, run:

     gcloud eventarc triggers list --location=us-central1
    

    The output is similar to the following:

     NAME                    TYPE                                      DESTINATION_RUN_SERVICE  DESTINATION_RUN_PATH  ACTIVE
     storage-events-trigger  google.cloud.storage.object.v1.finalized  helloworld-events                              Yes
    

Generate and view an event

  1. To generate an event, upload a text file to Cloud Storage:

     echo "Hello World" > random.txt
     gsutil 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, filter the log entries, and return the output in JSON format:

    gcloud logging read 'textPayload: "Detected change in Cloud Storage bucket"'
    
  3. Look for a log entry similar to the following:

    "textPayload": "2021/08/09 19:04:25 Detected change in Cloud Storage bucket: objects/random.txt"
    

Congratulations! You have successfully deployed an event receiver service to Cloud Run, created an Eventarc trigger, generated an event from Cloud Storage, and viewed it in the Cloud Run logs.

Clean up

To avoid incurring charges to your Google Cloud account for the resources used on this page, delete the Google Cloud project with the resources.

While Cloud Run does not charge when the service is not in use, you might still be charged for storing the container image in Container Registry, storing files in your Cloud Storage bucket, and Eventarc resources.

You can:

  1. Delete your image.

  2. Delete your storage bucket.

  3. Delete the Eventarc trigger.

Alternatively, you can delete your Google Cloud project to avoid incurring charges. Deleting your Google Cloud project stops billing for all the resources used within that project.

Delete a Google Cloud project:

gcloud projects delete PROJECT_ID

What's next