Use Eventarc to receive events from Cloud Storage

Stay organized with collections Save and categorize content based on your preferences.

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

This tutorial uses 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

Some of the steps in this document might not work correctly if your organization applies constraints to your Google Cloud environment. In that case, you might not be able to complete tasks like creating public IP addresses or service account keys. If you make a request that returns an error about constraints, see how to 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 and initialize the Google Cloud CLI.
  3. Create or select a Google Cloud project.

    • Create a Cloud project:

      gcloud projects create PROJECT_ID
    • Select the Cloud project that you created:

      gcloud config set project PROJECT_ID
  4. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.

  5. Install and initialize the Google Cloud CLI.
  6. Create or select a Google Cloud project.

    • Create a Cloud project:

      gcloud projects create PROJECT_ID
    • Select the Cloud project that you created:

      gcloud config set project PROJECT_ID
  7. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.

  8. 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
  9. Enable the APIs:
    gcloud services enable run.googleapis.com \
      eventarc.googleapis.com \
      storage.googleapis.com \
      cloudbuild.googleapis.com
  10. 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}
  11. Create a service account for the project. For example:
    gcloud iam service-accounts create sample-service-account \
      --description="A sample service account" \
      --display-name="Sample service account"
    After you create a service account, it can take up to 7 minutes before you can use the service account. If you try to use a service account immediately after you create it, and you receive an error, wait at least 60 seconds and try again.
  12. Confirm that sample-service-account has been created:
    gcloud iam service-accounts list
    The output should be similar to the following:
    DISPLAY NAME                     EMAIL                                                               DISABLED
    Default compute service account  PROJECT_NUMBER-compute@developer.gserviceaccount.com                False
    Sample service account           sample-service-account@PROJECT_ID.iam.gserviceaccount.com           False
  13. Grant the run.invoker role to the service account:
    gcloud projects add-iam-policy-binding PROJECT_ID \
      --member="serviceAccount:SERVICE_ACCOUNT_EMAIL" \
      --role="roles/run.invoker"
    Replace the following:
    • PROJECT_ID: the project ID
    • SERVICE_ACCOUNT_EMAIL: the service account email address returned in the previous step
  14. Grant the eventarc.admin role to the service account:
    gcloud projects add-iam-policy-binding PROJECT_ID \
      --member="serviceAccount:SERVICE_ACCOUNT_EMAIL"  \
      --role="roles/eventarc.admin"
  15. Grant the iam.serviceAccountUser role to the service account:
    gcloud iam service-accounts add-iam-policy-binding \
      SERVICE_ACCOUNT_ID@PROJECT_ID.iam.gserviceaccount.com \
      --member="serviceAccount:SERVICE_ACCOUNT_EMAIL" \
      --role="roles/iam.serviceAccountUser"
    Replace SERVICE_ACCOUNT_ID with the service account ID; for example, sample-service-account.
  16. Grant the pubsub.publisher role to the Cloud Storage 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"

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 an event receiver to Cloud Run

Deploy a Cloud Run service that receives and logs events.

  1. Clone the 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 gcr.io/${PROJECT_ID}/${SERVICE_NAME}
    
  4. Deploy the container image to Cloud Run:

    gcloud run deploy ${SERVICE_NAME} \
      --image gcr.io/${PROJECT_ID}/${SERVICE_NAME} \
      --region=${REGION}
    
  5. At the Allow unauthenticated invocations 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=SERVICE_ACCOUNT_EMAIL

    Replace SERVICE_ACCOUNT_EMAIL with the email address for the service account.

    This creates a trigger called helloworld-events.

  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=us-central1

    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
     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:

    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.

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

If you created a new project for this tutorial, delete the project. If you used an existing project and wish 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