Receive Pub/Sub events using an authenticated Cloud Run service


This tutorial shows how to deploy a containerized application using an authenticated Cloud Run service that receives events using Pub/Sub. Pub/Sub is a fully-managed real-time messaging service that lets you send and receive messages between independent applications.

Objectives

In this tutorial, you will:

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

  2. Create an Eventarc trigger that connects a Pub/Sub topic to the Cloud Run service.

  3. Publish a message to the Pub/Sub topic to generate an event.

  4. 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. 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. Update Google Cloud CLI components:
    gcloud components update
  11. Sign in using your account:
    gcloud auth login
  12. Enable the APIs:
    gcloud services enable artifactregistry.googleapis.com \
        cloudbuild.googleapis.com \
        eventarc.googleapis.com \
        pubsub.googleapis.com \
        run.googleapis.com
  13. 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}
    export SERVICE_NAME=trigger-pubsub
    
  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.

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

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.

Deploy an event receiver to Cloud Run

Deploy a Cloud Run service that logs the contents of an event.

  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.

    Ruby

    git clone https://github.com/GoogleCloudPlatform/ruby-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/pubsub/

    Python

    cd python-docs-samples/eventarc/pubsub/

    Go

    cd golang-samples/eventarc/pubsub/

    Java

    cd java-docs-samples/eventarc/pubsub/

    Ruby

    cd ruby-docs-samples/eventarc/pubsub/

    C#

    cd dotnet-docs-samples/eventarc/pubsub/
  3. Build the container and upload it to Cloud Build:

    gcloud builds submit --tag $REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY/trigger-pubsub:v1
  4. Deploy the container image to Cloud Run:

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

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

Create an Eventarc trigger

When a message is published to the Pub/Sub topic, the event triggers the Cloud Run service.

  1. Create a trigger to listen for Pub/Sub messages:

    New Pub/Sub topic

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

    This creates a new Pub/Sub topic and a trigger for it called trigger-pubsub.

    Existing Pub/Sub topic

      gcloud eventarc triggers create ${SERVICE_NAME} \
          --destination-run-service=${SERVICE_NAME} \
          --destination-run-region=${REGION} \
          --location=${REGION} \
          --event-filters="type=google.cloud.pubsub.topic.v1.messagePublished" \
          --transport-topic=projects/PROJECT_ID/topics/TOPIC_ID \
          --service-account=PROJECT_NUMBER-compute@developer.gserviceaccount.com
    

    Replace the following:

    • PROJECT_ID: your Google Cloud project ID
    • TOPIC_ID: the ID of the existing Pub/Sub topic

    This creates a trigger called trigger-pubsub for the existing Pub/Sub topic.

    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 returned trigger status should be ACTIVE: Yes.

Generate and view an event

Publish a message to a Pub/Sub topic to generate an event and trigger the Cloud Run service. The Cloud Run service logs the messages on the service logs.

  1. Find and set the Pub/Sub topic as an environment variable:

    export TOPIC_ID=$(gcloud eventarc triggers describe ${SERVICE_NAME} \
        --format='value(transport.pubsub.topic)')
    
  2. Send a message to the Pub/Sub topic to generate an event:

    gcloud pubsub topics publish $TOPIC_ID --message "Hello there"
    

    The event is sent to the Cloud Run service, which logs the event message.

  3. View the event-related log entries created by your service:

    gcloud logging read 'textPayload: "Hello there!"'

    The log entry should be similar to the following:

    textPayload: 'Hello, Hello there!'

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

Clean up

To avoid incurring charges such as storing the container image in Artifact Registry, storing files in your Cloud Storage bucket, and triggering Eventarc, you can delete the resources that you created for this tutorial:

  1. Delete the Cloud Run service.

  2. Delete your container image.

  3. Delete the Eventarc trigger.

Alternatively, you can delete your Google Cloud project. 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