Receive events using Pub/Sub messages (gcloud CLI)

This quickstart shows you how to set up a Google Kubernetes Engine (GKE) service as a destination to receive Pub/Sub topic events using Eventarc.

In this quickstart, you will:

  1. Complete preparatory tasks such as enabling APIs and setting up a service account.
  2. Create a GKE cluster.
  3. Initialize GKE destinations in Eventarc.
  4. Deploy a GKE service that receives events.
  5. Create an Eventarc trigger that connects a Pub/Sub topic to the GKE service.
  6. Generate and view a Pub/Sub event.

Before you begin

  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. Enable the Eventarc, Resource Manager, and Google Kubernetes Engine APIs:
    gcloud services enable eventarc.googleapis.com \
       cloudresourcemanager.googleapis.com \
       container.googleapis.com
  12. Set the configuration variables used in this quickstart:
    PROJECT_ID=$(gcloud config get-value project)
    CLUSTER_NAME=events-cluster
    SERVICE_NAME=hello-gke
    LOCATION=us-central1
  13. 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 quickstart, 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.

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

  15. Grant the Pub/Sub Subscriber role (roles/pubsub.subscriber) on the project to the Compute Engine default service account so that the Eventarc trigger can pull events from Pub/Sub.
    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \
        --role=roles/pubsub.subscriber
  16. 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 a GKE cluster

A GKE cluster consists of at least one cluster control plane machine and multiple worker machines called nodes. Nodes are Compute Engine virtual machine (VM) instances that run the Kubernetes processes necessary to make them part of the cluster. You deploy applications to clusters, and the applications run on the nodes.

Create an Autopilot cluster named events-cluster:

gcloud container clusters create-auto $CLUSTER_NAME \
    --region $LOCATION

It might take several minutes for the creation of the cluster to complete. Once the cluster is created, the output should be similar to the following:

Creating cluster events-cluster...done.
Created [https://container.googleapis.com/v1/projects/MY_PROJECT/zones/us-central1/clusters/events-cluster].
[...]
STATUS: RUNNING

This creates a GKE cluster named events-cluster in a project with a Google Cloud project ID of MY_PROJECT.

Enable GKE destinations

For each trigger that targets a GKE service, Eventarc creates an event forwarder component that pulls events from Pub/Sub and forwards it to the target. To create the component and manage resources in the GKE cluster, grant permissions to the Eventarc service agent:

  1. Enable GKE destinations for Eventarc:

    gcloud eventarc gke-destinations init
    
  2. At the prompt to bind the required roles, enter y.

    The following roles are bound to the service account:

    • compute.viewer
    • container.developer
    • iam.serviceAccountAdmin

Create a GKE service destination

Using a prebuilt image, gcr.io/cloudrun/hello, deploy a GKE service that will receive and log events:

  1. Kubernetes uses a YAML file called kubeconfig to store cluster authentication information for kubectl. Update the kubeconfig file with credentials and endpoint information to point kubectl at the GKE cluster:

    gcloud container clusters get-credentials $CLUSTER_NAME \
        --region $LOCATION
    
  2. Create a Kubernetes deployment:

    kubectl create deployment $SERVICE_NAME \
        --image=gcr.io/cloudrun/hello
    
  3. Expose it as a Kubernetes service:

    kubectl expose deployment $SERVICE_NAME \
        --type ClusterIP \
        --port 80 \
        --target-port 8080
    

Create an Eventarc trigger

When a message is published to the Pub/Sub topic, the Eventarc trigger sends messages to the hello-gke GKE service.

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

    New Pub/Sub topic

    gcloud eventarc triggers create gke-trigger-pubsub \
        --location="$LOCATION" \
        --destination-gke-cluster=$CLUSTER_NAME \
        --destination-gke-location=$LOCATION \
        --destination-gke-namespace=default \
        --destination-gke-service=$SERVICE_NAME \
        --destination-gke-path=/ \
        --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 gke-trigger-pubsub.

    Existing Pub/Sub topic

    gcloud eventarc triggers create gke-trigger-pubsub \
        --location="$LOCATION" \
        --destination-gke-cluster=$CLUSTER_NAME \
        --destination-gke-location=$LOCATION \
        --destination-gke-namespace=default \
        --destination-gke-service=$SERVICE_NAME \
        --destination-gke-path=/ \
        --event-filters="type=google.cloud.pubsub.topic.v1.messagePublished" \
        --service-account="PROJECT_NUMBER-compute@developer.gserviceaccount.com" \
        --transport-topic=projects/PROJECT_ID/topics/TOPIC_ID
    

    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 gke-trigger-pubsub for the existing Pub/Sub topic.
  2. Confirm the trigger was successfully created. It can take up to two minutes for the trigger to be fully functional.

     gcloud eventarc triggers list
    

    The output should be similar to the following:

    NAME: gke-trigger-pubsub
    TYPE: google.cloud.pubsub.topic.v1.messagePublished
    DESTINATION: GKE: hello-gke
    ACTIVE: Yes
    LOCATION: us-central1
    

Generate and viewing an event

You can generate an event to trigger the GKE service by publishing a message to the Pub/Sub topic. You can then view the message in the pod logs.

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

    TOPIC=$(gcloud eventarc triggers describe gke-trigger-pubsub \
        --location=us-central1 \
        --format='value(transport.pubsub.topic)')
    
  2. Send a message to the Pub/Sub topic to generate an event:

    gcloud pubsub topics publish $TOPIC --message="Hello World"
    

    The GKE service logs the event's message.

  3. To view the event message:

    1. Find the pod ID:

      kubectl get pods

      The output should be similar to the following:

      NAME                                         READY   STATUS             RESTARTS   AGE
      hello-gke-645964f578-2mjjt                   1/1     Running            0          35s

      Copy the NAME of the pod to use in the next step.

    2. Check the logs of the pod:

      kubectl logs NAME

      Replace NAME with the name of the pod you copied.

    3. Look for a log entry similar to:

      2022/02/24 22:23:49 Hello from Cloud Run! The container started successfully and is listening for HTTP requests on $PORT
      {"severity":"INFO","eventType":"google.cloud.pubsub.topic.v1.messagePublished","message":"Received event of type google.cloud.pubsub.topic.v1.messagePublished. Event data: Hello World"[...]}
      

Clean up

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, Eventarc resources, Pub/Sub messages, and for the GKE cluster.

You can delete your image, delete the Pub/Sub topic, delete the Pub/Sub subscription, and delete the GKE cluster.

To delete the Eventarc trigger:

gcloud eventarc triggers delete gke-trigger-pubsub

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.

gcloud projects delete PROJECT_ID_OR_NUMBER

Replace PROJECT_ID_OR_NUMBER with the project ID or number.

What's next

Receive events using Cloud Audit Logs (Google Cloud CLI)