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

<br />

This quickstart shows you how to deploy an *unauthenticated*
Cloud Run service that receives events using Pub/Sub.


> [!NOTE]
> **Note:** All Cloud Run services are deployed privately by default, which means that they can't be accessed without providing authentication credentials in the request. For projects with [domain restricted sharing organization policies](https://docs.cloud.google.com/resource-manager/docs/organization-policy/restricting-domains), use an authenticated Cloud Run target service rather than one that allows [public access](https://docs.cloud.google.com/run/docs/authenticating/public.md.txt).

<br />

In this quickstart, you:

1. Deploy an event receiver service to Cloud Run.

2. Create an Eventarc trigger.

3. Publish a message to a Pub/Sub topic to generate an event,
   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](https://docs.cloud.google.com/resource-manager/docs/organization-policy/develop-apps-constrained-environment).

1. 
2. Update Google Cloud CLI components:

   ```bash
   gcloud components update
   ```
3. Sign in using your account:

   ```bash
   gcloud auth login
   ```
4. Set the configuration variables used in this quickstart:

   ```bash
   gcloud config set run/region us-central1
   gcloud config set run/platform managed
   gcloud config set eventarc/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:

   - [Cloud Run Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/run.md.txt#run.admin) (`roles/run.admin`)
   - [Eventarc Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/eventarc.md.txt#eventarc.admin) (`roles/eventarc.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. 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
   ```
8. 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)'
```

<br />

## Deploy an event receiver to Cloud Run

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

```bash
gcloud run deploy helloworld-events-pubsub-quickstart \
    --image=us-docker.pkg.dev/cloudrun/container/hello \
    --allow-unauthenticated
```

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

## Create an Eventarc trigger

The event trigger sends messages to the event receiver service deployed on
Cloud Run when a message is published to the
Pub/Sub topic.

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

   ### New Pub/Sub topic

   ```bash
   gcloud eventarc triggers create events-pubsub-trigger \
       --destination-run-service=helloworld-events-pubsub-quickstart \
       --destination-run-region=us-central1 \
       --event-filters="type=google.cloud.pubsub.topic.v1.messagePublished"
   ```

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

   ### Existing Pub/Sub topic

   ```bash
   gcloud eventarc triggers create events-pubsub-trigger \
       --destination-run-service=helloworld-events-pubsub-quickstart \
       --destination-run-region=us-central1 \
       --event-filters="type=google.cloud.pubsub.topic.v1.messagePublished" \
       --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 `events-pubsub-trigger` 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](https://docs.cloud.google.com/eventarc/docs/troubleshooting.md.txt#trigger-error).

   <br />

2. Confirm that the trigger was successfully created:

       gcloud eventarc triggers list --location=us-central1

   The `events-pubsub-trigger` is listed with a destination that is the
   Cloud Run service, `helloworld-events-pubsub-quickstart`.

> [!NOTE]
> **Note:** Although your trigger is created immediately, it can take up to two minutes for triggers to be fully functional.

## Generate and view a Pub/Sub topic event

You can generate an Eventarc event by publishing a message to a
Pub/Sub topic.

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

       export RUN_TOPIC=$(gcloud eventarc triggers describe events-pubsub-trigger \
           --format='value(transport.pubsub.topic)')

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

       gcloud pubsub topics publish $RUN_TOPIC --message "Hello World!"

   The event is routed to the Cloud Run service, which
   logs the event message.
3. To view the event-related log entries created by your service, run the
   following command:

   ```
   gcloud logging read 'jsonPayload.message: "Received event of type google.cloud.pubsub.topic.v1.messagePublished"'
   ```
4. Look for a log entry similar to:

   ```
   jsonPayload:
   ...
   message: 'Received event of type google.cloud.pubsub.topic.v1.messagePublished.
       Event data: Hello World!'
   ```

   > [!NOTE]
   > **Note:** If you don't see a log entry, wait a few minutes and retry the `gcloud logging read` command. The trigger can take up to two minutes after creation to start filtering events.

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

## 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 Cloud Run service](https://docs.cloud.google.com/run/docs/managing/services.md.txt#delete).

2. [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.

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 Pub/Sub events using an authenticated Cloud Run service](https://docs.cloud.google.com/eventarc/standard/docs/run/pubsub-authenticated.md.txt)
- [Build containers for Cloud Run](https://docs.cloud.google.com/run/docs/building/containers.md.txt)
- [Develop services for Cloud Run](https://docs.cloud.google.com/run/docs/developing.md.txt)