# Receive events using Pub/Sub messages (gcloud CLI)

<br />

> [!WARNING]
>
> **Preview**
>
>
> This product is
>
> subject to the "Pre-GA Offerings Terms" in the General Service Terms section of the
> [Service Specific
> Terms](https://docs.cloud.google.com/terms/service-terms#1).
>
> Pre-GA products are available "as is" and might have limited support.
>
> For more information, see the
> [launch stage descriptions](https://cloud.google.com/products/#product-launch-stages).

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.

> [!NOTE]
> **Note:** Support for GKE as an Eventarc destination includes the public endpoints of private and public services running in a GKE cluster.

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. 
2. Update Google Cloud CLI components:

   ```bash
   gcloud components update
   ```
3. Enable the Eventarc, Resource Manager, and Google Kubernetes Engine APIs:

   ```bash
   gcloud services enable eventarc.googleapis.com \
      cloudresourcemanager.googleapis.com \
      container.googleapis.com
   ```
4. Set the configuration variables used in this quickstart:

   ```bash
   PROJECT_ID=$(gcloud config get-value project)
   CLUSTER_NAME=events-cluster
   SERVICE_NAME=hello-gke
   LOCATION=us-central1
   ```
5. If you are the project creator, you are granted the
   [basic Owner role](https://docs.cloud.google.com/iam/docs/roles-overview.md.txt#basic)
   (`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](https://docs.cloud.google.com/eventarc/docs/all-roles-permissions.md.txt) 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:

   - [Eventarc Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/eventarc.md.txt#eventarc.admin) (`roles/eventarc.admin`)
   - [Kubernetes Engine Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/container.md.txt#container.admin) (`roles/container.admin`)
   - [Logs View Accessor](https://docs.cloud.google.com/iam/docs/roles-permissions/logging.md.txt#logging.viewAccessor) (`roles/logging.viewAccessor`)
   - [Project IAM Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/resourcemanager.md.txt#resourcemanager.projectIamAdmin) (`roles/resourcemanager.projectIamAdmin`)
   - [Pub/Sub Publisher](https://docs.cloud.google.com/iam/docs/roles-permissions/pubsub.md.txt#pubsub.publisher) (`roles/pubsub.publisher`)
   - [Service Account Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/iam.md.txt#iam.serviceAccountAdmin) (`roles/iam.serviceAccountAdmin`)
   - [Service Account User](https://docs.cloud.google.com/iam/docs/roles-permissions/iam.md.txt#iam.serviceAccountUser) (`roles/iam.serviceAccountUser`)
   - [Service Usage Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/serviceusage.md.txt#serviceusage.serviceUsageAdmin) (`roles/serviceusage.serviceUsageAdmin`)


   For more information about granting roles, see [Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access.md.txt).


   You might also be able to get
   the required permissions through [custom
   roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles) or other [predefined
   roles](https://docs.cloud.google.com/iam/docs/roles-overview#predefined).
6. 
7. Make note of the [Compute Engine
   default service account](https://docs.cloud.google.com/iam/docs/service-account-types#default) as you will 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:

   ```bash
   PROJECT_NUMBER-compute@developer.gserviceaccount.com
   ```

   Replace `PROJECT_NUMBER` with your Google Cloud
   project number. You can find your project number on the
   [Welcome](https://console.cloud.google.com/welcome)
   page of the Google Cloud console or by running the following command:

   ```bash
   gcloud projects describe PROJECT_ID --format='value(projectNumber)'
   ```

   For production environments, we strongly recommend
   [creating a new service account](https://docs.cloud.google.com/iam/docs/service-accounts-create.md.txt)
   and granting it one or more IAM roles that contain the
   [minimum permissions required](https://docs.cloud.google.com/iam/docs/best-practices-service-accounts.md.txt#limit-service-account-privileges)
   and follow the principle of [least privilege](https://docs.cloud.google.com/iam/docs/using-iam-securely.md.txt#least_privilege).

   > [!NOTE]
   > **Note:**
   >
   >
   > The [`iam.automaticIamGrantsForDefaultServiceAccounts` organization policy constraint](https://docs.cloud.google.com/resource-manager/docs/organization-policy/restricting-service-accounts#disable_service_account_default_grants)
   > prevents the Editor role from being automatically granted to default service accounts. If you
   > created your organization after May 3, 2024, this constraint is enforced by
   > default.
   >
   >
   > We strongly recommend that you enforce this constraint to disable the automatic role grant. If you
   > disable the automatic role grant, you must decide which roles to grant to the default service
   > accounts, and then [grant these roles](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access.md.txt)
   > yourself.
   >
   >
   > If the default service account already has the Editor role, we recommend that you replace the
   > Editor role with less permissive roles.To safely modify the service account's roles, use [Policy Simulator](https://docs.cloud.google.com/policy-intelligence/docs/simulate-iam-policies.md.txt) to see the impact of
   > the change, and then [grant and revoke the
   > appropriate roles](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access).

8. 
9. Grant the [Pub/Sub
   Subscriber role](https://docs.cloud.google.com/iam/docs/roles-permissions/pubsub#pubsub.subscriber) (`roles/pubsub.subscriber`) on the project to the Compute Engine default service account so that the Eventarc trigger can pull events from Pub/Sub.

   ```bash
   gcloud projects add-iam-policy-binding PROJECT_ID \
       --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \
       --role=roles/pubsub.subscriber
   ```
10. 
11. 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](https://docs.cloud.google.com/iam/docs/roles-permissions/iam#iam.serviceAccountTokenCreator) (`roles/iam.serviceAccountTokenCreator`) to the service agent. Otherwise, this role is granted by default:

    ```bash
    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-pubsub.iam.gserviceaccount.com \
        --role=roles/iam.serviceAccountTokenCreator
    ```

<br />

## Create a GKE cluster

A GKE [cluster](https://docs.cloud.google.com/kubernetes-engine/docs/concepts/cluster-architecture.md.txt)
consists of at least one cluster control plane machine and multiple worker
machines called nodes. Nodes are
[Compute Engine virtual machine (VM) instances](https://docs.cloud.google.com/compute/docs/instances.md.txt)
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`:

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

   ```bash
   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

Deploy a GKE service that will receive and log events using a
prebuilt image, `us-docker.pkg.dev/cloudrun/container/hello`:

1. Kubernetes uses a YAML file called
   [`kubeconfig`](https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/)
   to store cluster authentication information for `kubectl`. Update the
   `kubeconfig` file with credentials and endpoint information to
   point `kubectl` at the GKE cluster:

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

   ```bash
   kubectl create deployment $SERVICE_NAME \
       --image=us-docker.pkg.dev/cloudrun/container/hello
   ```
3. Expose it as a Kubernetes service:

   ```bash
   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

   ```bash
   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

   ```bash
   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.

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

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

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

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

      ```bash
      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

When you finish the tasks that are described in this document, you can avoid
continued billing by deleting the resources that you created.

You can:

1. [Delete the Eventarc trigger](https://docs.cloud.google.com/eventarc/docs/managing-triggers.md.txt#deleting_triggers).

   This also deletes the associated Pub/Sub topic.
2. [Delete the GKE cluster](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/deleting-a-cluster.md.txt#deleting_a_cluster).

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.

> [!CAUTION]
> **Caution** : Deleting a project has the following effects:
>
> - **Everything in the project is deleted.** If you used an existing project for the tasks in this document, when you delete it, you also delete any other work you've done in the project.
> - **Custom project IDs are lost.** When you created this project, you might have created a custom project ID that you want to use in the future. To preserve the URLs that use the project ID, such as an `appspot.com` URL, delete selected resources inside the project instead of deleting the whole project.

Delete a Google Cloud project:

```
gcloud projects delete PROJECT_ID
```

If you plan to explore multiple tutorials and quickstarts, reusing projects can
help you avoid exceeding project quota limits.

## What's next

[Receive events using Cloud Audit Logs (Google Cloud CLI)](https://docs.cloud.google.com/eventarc/standard/docs/gke/quickstart-cal.md.txt)