# Publish events to a Cloud Run job

<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. Deploy a Cloud Run job from source code.

2. Create an Eventarc Advanced bus.

3. Create an Eventarc Advanced enrollment.

4. Publish an event message to the bus.

5. Confirm that the Cloud Run job successfully executed.

You can complete this quickstart using the gcloud CLI.

## 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---for example, `us-central1`.
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).

   #### 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 Developer](https://docs.cloud.google.com/iam/docs/roles-permissions/run.md.txt#run.developer) (`roles/run.developer`)
   - [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. To give Eventarc Advanced the necessary permissions to execute a Cloud Run job, ask your administrator to grant the [Cloud Run
   Invoker](https://docs.cloud.google.com/iam/docs/roles-permissions/run#run.invoker) (`roles/run.invoker`) IAM role on your Google Cloud project to a service account:

   > [!NOTE]
   > Note: To execute a job that overrides the job configuration (for example, by [defining a message binding](https://docs.cloud.google.com/eventarc/advanced/docs/receive-events/transform-events.md.txt#message-binding)), you must grant the **Cloud Run
   > Developer** (`roles/run.developer`) or **Cloud Run Jobs Executor
   > With Overrides** (`roles/run.jobsExecutorWithOverrides`) IAM role. For more information, see [Override job
   > configuration for a specific execution](https://docs.cloud.google.com/run/docs/execute/jobs#override-job-configuration).

   1. Create a service account. For testing purposes, you will attach this service account to an Eventarc Advanced pipeline to represent the identity of the pipeline.

      ```bash
      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME
      ```
      Replace `SERVICE_ACCOUNT_NAME` with a name for your service account.
   2. Grant the `roles/run.invoker` IAM role to the service account:

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

<br />

## Deploy a Cloud Run job from source code

Deploy a [Cloud Run job](https://docs.cloud.google.com/run/docs/create-jobs.md.txt) as your event
destination. Unlike a Cloud Run service, which listens for and
serves requests, a Cloud Run job only runs its tasks and exits
when finished. A job does not listen for or serve requests.

Other event destinations---such as a Pub/Sub topic, Workflows,
or another HTTP endpoint---are supported. For more information, see
[Event providers and destinations](https://docs.cloud.google.com/eventarc/advanced/docs/event-providers-targets.md.txt).

Create a job from Python source code by using the
[gcloud run jobs deploy](https://docs.cloud.google.com/sdk/gcloud/reference/run/jobs/deploy.md.txt) command. Your
code is automatically packaged into a container image, uploaded to Artifact Registry,
and then deployed to Cloud Run.

1. Create a directory named `jobs` and navigate to it:

       mkdir jobs
       cd jobs

2. Create a `main.py` file and copy the following sample code into it:

   ```python
   import os

   TASK_INDEX = os.getenv("CLOUD_RUN_TASK_INDEX", 0)

   def main():
       """
       This job prints "Hello world"
       """
       print(f"Starting task #{TASK_INDEX}...")
       print("Hello world")
       print(f"Completed task #{TASK_INDEX}.")

   # Start script
   if __name__ == "__main__":
       main()
   ```
3. Create a text file named `Procfile` with no file extension and copy the
   following text into it:

       web: python3 main.py

4. Deploy the job:

   ```bash
   gcloud run jobs deploy JOB_NAME \
       --source . \
       --tasks 1 \
       --region=$REGION
   ```

   Replace `JOB_NAME` with a unique name for the
   Cloud Run job---for example, `my-job`.

## 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 of your bus or a fully
qualified name---for example, `my-bus`.

## Create an Eventarc Advanced enrollment

An enrollment determines which messages are routed to a destination. It also
specifies the pipeline used to configure the destination for the event messages.
In this case, the target destination is a Cloud Run job.

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

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

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

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='JOB_URI',http_endpoint_message_binding_template='{"body": ""}',oauth_token_authentication_service_account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com \
       --input-payload-format-json= \
       --location=$REGION
   ```

   Replace the following:
   - `PIPELINE_NAME`: the ID of the pipeline or a fully qualified name---for example, `my-pipeline`.
   - `JOB_URI`: the URI of the
     Cloud Run job in the following format:

     ```bash
     https://REGION-run.googleapis.com/apis/run.googleapis.com/v1/namespaces/PROJECT_NUMBER/jobs/JOB_NAME:run
     ```

     You can retrieve your project number by running the following command:

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

   Note the following:
   - The `http_endpoint_message_binding_template` key transforms the event into the format expected by the [Cloud Run Admin API](https://docs.cloud.google.com/run/docs/reference/rest/v2/projects.locations.jobs/run.md.txt). When defining a [message binding](https://docs.cloud.google.com/eventarc/advanced/docs/receive-events/transform-events.md.txt#message-binding), you must configure an input format to access the payload---for example: `{"body": ""}`.
   - The `oauth_token_authentication_service_account` key specifies a service account email. This email is used to generate an [OAuth token](https://developers.google.com/identity/protocols/OAuth2) typically used only when calling Google APIs hosted on `*.googleapis.com`.
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---for example, `my-enrollment`.
   - `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, 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, 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

Publish an event to a bus by 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

Publish an event to a bus as a JSON message by 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.

## Confirm that the Cloud Run job successfully executed

After publishing an event to your Eventarc Advanced bus, check
the logs of your Cloud Run job to verify that the
Cloud Run job successfully executed and that "Hello world" was printed.
It might take a few minutes before the job runs and completes.

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"'
   ```
2. Look for a log entry similar to the following:

   ```
   insertId: 693c8dd0000cb2976d7966b8
   ...
   labels:
       job_name: JOB_NAME
       location: REGION
       project_id: PROJECT_ID
   type: cloud_run_job
   textPayload: Hello world
   timestamp: '2025-12-12T21:49:04.832151Z'
   ```

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

3. You can also confirm that the Cloud Run job executed
   successfully by using the
   [`gcloud run jobs describe`](https://docs.cloud.google.com/sdk/gcloud/reference/run/jobs/describe) command:

   ```
   gcloud run jobs describe JOB_NAME \
       --region=$REGION
   ```

   You should receive output similar to the following:

   ```
   ✔ Job JOB_NAME in region us-central1
   Executed 1 time
   ...
   ```

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.

## Clean up

To help avoid continued billing after you finish this quickstart, delete the resources that you created:

<br />

1. [Delete a Cloud Run job](https://docs.cloud.google.com/run/docs/managing/jobs.md.txt#delete).

2. 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, delete your Google Cloud project to help 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)
- [Troubleshoot issues](https://docs.cloud.google.com/eventarc/advanced/docs/troubleshoot.md.txt)