# Publish and receive events by creating a bus and enrollment (gcloud CLI)

<br />

This quickstart shows you how to publish and receive event messages by creating
an Eventarc Advanced bus and enrollment in your Google Cloud
project.

- A *bus* acts as a central router, receiving messages from event sources or
  published by providers.

- An *enrollment* routes messages received by the bus to one or more
  destinations through a processing *pipeline*.

In this quickstart, you:

1. Create an Artifact Registry standard repository.

2. Deploy an event receiver service to Cloud Run.

3. Create an Eventarc Advanced bus.

4. Create an Eventarc Advanced enrollment.

5. Publish an event message to the bus.

6. View the event data in the Cloud Run logs.

You can complete this quickstart using the gcloud CLI. To complete
the steps using the Google Cloud console, see
[Publish and receive events by creating a bus and enrollment (console)](https://docs.cloud.google.com/eventarc/advanced/docs/quickstarts/publish-events-create-bus-console.md.txt).

## 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. Update `gcloud` components:

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

   ```
   gcloud auth login
   ```
3. Set the configuration variable used in this quickstart:

   ```
   REGION=REGION
   ```

   Replace `REGION` with a
   [supported location](https://docs.cloud.google.com/eventarc/docs/locations.md.txt#advanced-regions) for
   the bus.
4. 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).

   Note that by default,
   [Cloud Build
   permissions include permissions to upload and download Artifact Registry
   artifacts](https://docs.cloud.google.com/artifact-registry/docs/access-control#gcp).

   #### 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 Build Editor](https://docs.cloud.google.com/iam/docs/roles-permissions/cloudbuild.md.txt#cloudbuild.builds.editor) (`roles/cloudbuild.builds.editor`)
   - [Cloud Run Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/run.md.txt#run.admin) (`roles/run.admin`)
   - [Eventarc Developer](https://docs.cloud.google.com/iam/docs/roles-permissions/eventarc.md.txt#eventarc.developer) (`roles/eventarc.developer`)
   - [Eventarc Message Bus Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/eventarc.md.txt#eventarc.messageBusAdmin) (`roles/eventarc.messageBusAdmin`)
   - [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`)
   - [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).
5. For testing purposes, create a service account, and grant it the roles necessary to complete this quickstart.
   1. Create a service account:

      ```bash
      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME
      ```
      Replace `SERVICE_ACCOUNT_NAME` with a name for your service account.
   2. Grant the roles necessary to build and deploy a container image, and to represent the identity of an Eventarc Advanced pipeline:
      - [Artifact Registry
        Writer](https://docs.cloud.google.com/iam/docs/roles-permissions/artifactregistry#artifactregistry.writer): to upload Artifact Registry artifacts
      - [Logs
        Writer](https://docs.cloud.google.com/iam/docs/roles-permissions/logging#logging.logWriter): to write logs to Cloud Logging
      - [Storage
        Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/storage#storage.admin): to access Cloud Storage objects
      - [Cloud Run
        Invoker](https://docs.cloud.google.com/iam/docs/roles-permissions/run#run.invoker): to call Cloud Run

      ```bash
      gcloud projects add-iam-policy-binding PROJECT_ID \
          --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" \
          --role=roles/artifactregistry.writer
      gcloud projects add-iam-policy-binding PROJECT_ID \
          --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" \
          --role=roles/logging.logWriter
      gcloud projects add-iam-policy-binding PROJECT_ID \
          --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" \
          --role=roles/storage.admin
      gcloud projects add-iam-policy-binding PROJECT_ID \
          --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" \
          --role=roles/run.invoker
      ```

   Note that you can configure who can access your Cloud Run
   service in either of the following ways:
   - Grant permission to select service accounts or groups to allow access to the service. All requests must have an HTTP Authorization header containing an OpenID Connect token signed by Google for one of the authorized service accounts. This is the way that access is configured in this quickstart.
   - Grant permission to [`allUsers`](https://docs.cloud.google.com/iam/docs/principals-overview.md.txt#all-users) to allow unauthenticated access.

   For more information, see
   [Access control for Cloud Run](https://docs.cloud.google.com/run/docs/securing/security.md.txt#access-control).

<br />

## Create an Artifact Registry standard repository

Create an
[Artifact Registry standard repository](https://docs.cloud.google.com/artifact-registry/docs/repositories/create-repos.md.txt)
to store your container image.

```bash
gcloud artifacts repositories create REPOSITORY \
    --repository-format=docker \
    --location=$REGION
```

Replace `REPOSITORY` with a unique name for the
Artifact Registry repository---for example, `my-repo`.

## Deploy an event receiver service to Cloud Run

Deploy a [Cloud Run service](https://docs.cloud.google.com/run/docs/overview/what-is-cloud-run.md.txt)
that logs the contents of an event. Other event destinations are supported such
as a Pub/Sub topic, Workflows, or an HTTP endpoint. For more
information, see
[Event providers and destinations](https://docs.cloud.google.com/eventarc/advanced/docs/event-providers-targets.md.txt).

1. Clone the GitHub repository:

   ```bash
   git clone https://github.com/GoogleCloudPlatform/eventarc-samples.git
   ```
2. Change to the directory that contains the Cloud Run sample
   code:

   ```bash
   cd eventarc-samples/eventarc-advanced-quickstart/
   ```
3. Build a Docker container image and push the image to your repository:

   ```bash
   gcloud builds submit \
       --tag $REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY/log-events:v1 \
       --service-account=projects/PROJECT_ID/serviceAccounts/SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com \
       --default-buckets-behavior=regional-user-owned-bucket
   ```
4. Deploy the container image to Cloud Run:

   ```bash
   gcloud run deploy SERVICE_NAME \
       --image $REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY/log-events:v1 \
       --platform managed \
       --ingress all \
       --no-allow-unauthenticated \
       --region=$REGION
   ```

   Replace `SERVICE_NAME` with the name of your
   service---for example, `my-service`.

   The ingress setting of `all` allows all requests, including requests
   directly from the internet to the `run.app` URL. For more information, see
   [Restrict network ingress for Cloud Run](https://docs.cloud.google.com/run/docs/securing/ingress.md.txt).

   The `--no-allow-unauthenticated` flag configures the service to only allow
   authenticated invocations.

When you see the Cloud Run service URL, the deployment is
complete. Note this URL so that you can use it in a subsequent step.

## Create an Eventarc Advanced bus

A bus receives event messages from a message source or published by a provider
and acts as a message router.

For more information, see
[Create a bus to route messages](https://docs.cloud.google.com/eventarc/advanced/docs/publish-events/create-bus.md.txt).

> [!NOTE]
> **Note:** You can create one bus per Google Cloud project per [supported region](https://docs.cloud.google.com/eventarc/docs/locations.md.txt#advanced-regions).

Create an Eventarc Advanced bus in your project by using the
[`gcloud eventarc message-buses create`](https://docs.cloud.google.com/sdk/gcloud/reference/eventarc/message-buses/create)
command:

```bash
gcloud eventarc message-buses create BUS_NAME \
    --location=$REGION
```

Replace `BUS_NAME` with the ID or fully qualified
identifier of your bus---for example, `my-bus`.

## Create an Eventarc Advanced enrollment

An enrollment determines which messages are routed to a destination and it also
specifies the pipeline that is used to configure a destination for the event
messages.

For more information, see
[Create an enrollment to receive events](https://docs.cloud.google.com/eventarc/advanced/docs/receive-events/create-enrollment.md.txt).

> [!NOTE]
> **Note:** Creating a pipeline might take more than 10 minutes.

When using the gcloud CLI, you first create a pipeline, and then
create an enrollment:

1. Create a pipeline by using the
   [`gcloud eventarc pipelines create`](https://docs.cloud.google.com/sdk/gcloud/reference/eventarc/pipelines/create.md.txt)
   command:

   ```bash
   gcloud eventarc pipelines create PIPELINE_NAME \
       --destinations=http_endpoint_uri='CLOUD_RUN_SERVICE_URL',google_oidc_authentication_service_account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com \
       --location=$REGION
   ```

   Replace the following:
   - `PIPELINE_NAME`: the ID of the pipeline or a fully qualified name.
   - `CLOUD_RUN_SERVICE_URL`: the fully qualified URL of your Cloud Run service---for example, `https://SERVICE_NAME-abcdef-uc.a.run.app`. This is the destination for your event messages.

   Note that the `google_oidc_authentication_service_account` key specifies a
   service account email which is used to generate an
   [OIDC token](https://developers.google.com/identity/protocols/OpenIDConnect).
2. Create an enrollment by using the
   [`gcloud eventarc enrollments create`](https://docs.cloud.google.com/sdk/gcloud/reference/eventarc/enrollments/create)
   command:

   ```bash
   gcloud eventarc enrollments create ENROLLMENT_NAME \
       --cel-match=MATCH_EXPRESSION \
       --destination-pipeline=PIPELINE_NAME \
       --message-bus=BUS_NAME \
       --message-bus-project=PROJECT_ID \
       --location=$REGION
   ```

   Replace the following:
   - `ENROLLMENT_NAME`: the ID of the enrollment or a fully qualified name.
   - `MATCH_EXPRESSION`: the matching expression for
     this enrollment
     [using CEL](https://docs.cloud.google.com/eventarc/advanced/docs/receive-events/use-cel.md.txt)---for example:

     ```bash
     "message.type == 'hello-world-type'"
     ```

## Publish an event message to the bus

To directly publish a message to your bus, you can use the
[`gcloud eventarc message-buses publish`](https://docs.cloud.google.com/sdk/gcloud/reference/eventarc/message-buses/publish)
command or send a request to the
[Eventarc Publishing REST API](https://docs.cloud.google.com/eventarc/docs/reference/publishing/rest.md.txt).
For more information, see
[Publish events directly](https://docs.cloud.google.com/eventarc/advanced/docs/publish-events/publish-events-direct-format.md.txt).

The message must be in a CloudEvents format which is a specification for
describing event data in a common way. The `data` element is the payload of your
event. Any well-formed JSON can go in this field. For more information about
CloudEvents context attributes, see
[Event format](https://docs.cloud.google.com/eventarc/advanced/docs/event-format.md.txt).

The following are examples of directly publishing an event to an
Eventarc Advanced bus:

### Example 1

You can publish an event to a bus using the gcloud CLI and an
`--event-data` and other event attribute flags:

```bash
gcloud eventarc message-buses publish BUS_NAME \
    --event-data='{"key": "hello-world-data"}' \
    --event-id=hello-world-id-1234 \
    --event-source=hello-world-source \
    --event-type=hello-world-type \
    --event-attributes="datacontenttype=application/json" \
    --location=$REGION
```

### Example 2

You can publish an event to a bus as a JSON message using the gcloud CLI
and a `--json-message` flag:

```bash
gcloud eventarc message-buses publish BUS_NAME \
    --location=$REGION \
    --json-message='{"id": "hello-world-id-1234", "type":
 "hello-world-type", "source":
 "hello-world-source", "specversion": "1.0", "data":
 {"key": "hello-world-data"}}'
```

After publishing an event, you should receive an "Event published successfully"
message.

## View the event data in the Cloud Run logs

After publishing an event to your Eventarc Advanced bus, you can
check the logs of your Cloud Run service to verify that the event
was received as expected.

1. Filter the log entries and return the output by using the
   [`gcloud logging read`](https://docs.cloud.google.com/sdk/gcloud/reference/logging/read.md.txt) command:

   ```
   gcloud logging read 'textPayload: "hello-world-data"'
   ```
2. Look for a log entry similar to the following:

   ```
   insertId: 670808e70002b5c6477709ae
   labels:
   instanceId: 007989f2a10a4a33c21024f2c8e06a9de65d9b4fdc2ee27697a50379b3fab2f975b9233dc357d50b06270829b9b479d5a1ee54a10fa2cb2d98c5f77a0895e2be0f9e6e4b20
   logName: projects/PROJECT_ID/logs/run.googleapis.com%2Fstderr
   receiveTimestamp: '2024-10-10T17:03:35.424659450Z'
   resource:
   labels:
   ...
   type: cloud_run_revision
   textPayload: "[2024-10-21 15:33:19,581] INFO in server: Body: b'{\"value\":\"hello-world-data\"\
     }'"
   timestamp: '2024-10-10T17:03:35.177606Z'
   ```

   > [!NOTE]
   > **Note:** If you don't see a log entry, wait a few minutes and retry the `gcloud logging read` command.

You have successfully created an Eventarc Advanced bus and
enrollment, published an event message to the bus, and verified the expected
outcome in the logs of the event receiver service.

## Clean up

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

1. [Delete an Artifact Registry repository](https://docs.cloud.google.com/artifact-registry/docs/repositories/delete-repos.md.txt).

2. [Delete a Cloud Run service](https://docs.cloud.google.com/run/docs/managing/services.md.txt#delete).

3. Delete Eventarc Advanced resources:

   1. [Delete an enrollment](https://docs.cloud.google.com/eventarc/advanced/docs/receive-events/create-enrollment.md.txt#delete-enrollment).

   2. [Delete a pipeline](https://docs.cloud.google.com/eventarc/advanced/docs/receive-events/create-enrollment.md.txt#delete-pipeline).

   3. [Delete a bus](https://docs.cloud.google.com/eventarc/advanced/docs/publish-events/create-bus.md.txt#delete-bus).

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.
>
>
> If you plan to explore multiple architectures, tutorials, or quickstarts, reusing projects
> can help you avoid exceeding project quota limits.

Delete a Google Cloud project:

```
gcloud projects delete PROJECT_ID
```

## What's next

- [Publish events from Google sources](https://docs.cloud.google.com/eventarc/advanced/docs/publish-events/publish-events-google-sources.md.txt)
- [Publish events directly](https://docs.cloud.google.com/eventarc/advanced/docs/publish-events/publish-events-direct-format.md.txt)
- [Transform received events](https://docs.cloud.google.com/eventarc/advanced/docs/receive-events/transform-events.md.txt)
- [Format received events](https://docs.cloud.google.com/eventarc/advanced/docs/receive-events/configure-format-events.md.txt)