Create trigger (v1)

Create a new Eventarc trigger that routes Pub/Sub events to a Cloud Run service.

Code sample

Java

To authenticate to Eventarc, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.eventarc.v1.CloudRun;
import com.google.cloud.eventarc.v1.Destination;
import com.google.cloud.eventarc.v1.EventFilter;
import com.google.cloud.eventarc.v1.EventarcClient;
import com.google.cloud.eventarc.v1.LocationName;
import com.google.cloud.eventarc.v1.Trigger;
import com.google.cloud.eventarc.v1.TriggerName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateTrigger {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    String triggerId = "example-trigger-id";
    String projectId = "example-project-id";
    String locationId = "us-central1";
    String serviceId = "example-service-id";
    createTrigger(triggerId, projectId, locationId, serviceId);
  }

  public static void createTrigger(
      String triggerId, String projectId, String locationId, String serviceId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    try (EventarcClient client = EventarcClient.create()) {
      String parent = LocationName.of(projectId, locationId).toString();

      CloudRun cloudRun =
          CloudRun.newBuilder()
              .setService(serviceId)
              .setRegion(locationId)
              .build();

      Destination destination =
          Destination.newBuilder()
              .setCloudRun(cloudRun)
              .build();

      EventFilter eventFilter =
          EventFilter.newBuilder()
              .setAttribute("type")
              .setValue("google.cloud.pubsub.topic.v1.messagePublished")
              .build();

      Trigger trigger =
          Trigger.newBuilder()
              .setName(TriggerName.of(projectId, locationId, triggerId).toString())
              .setDestination(destination)
              .addEventFilters(eventFilter)
              .build();

      Trigger response =
          client.createTriggerAsync(parent, trigger, triggerId).get(3, TimeUnit.MINUTES);
      System.out.println("Created trigger: " + response.getName());
    }
  }
}

Node.js

To authenticate to Eventarc, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

'use strict';

const {EventarcClient} = require('@google-cloud/eventarc');
const {status} = require('@grpc/grpc-js');

const client = new EventarcClient();

/**
 * Creates an Eventarc trigger targeting a Cloud Run service.
 *
 * @param {string} triggerId - ID to assign to the trigger (for example, 'example-trigger').
 * @param {string} projectId - The Google Cloud project ID.
 * @param {string} locationId - The Google Cloud region for the trigger (for example, 'us-central1').
 * @param {string} cloudRunServiceId - The name of the destination Cloud Run service.
 */
async function createTrigger(triggerId, projectId, locationId, cloudRunServiceId) {
  try {
    const parent = `projects/${projectId}/locations/${locationId}`;
    const trigger = {
      name: `${parent}/triggers/${triggerId}`,
      eventFilters: [
        {
          attribute: 'type',
          value: 'google.cloud.pubsub.topic.v1.messagePublished',
        },
      ],
      destination: {
        cloudRun: {
          service: cloudRunServiceId,
          region: locationId,
        },
      },
    };

    // CreateTrigger initiates a long-running operation.
    const [operation] = await client.createTrigger({
      parent,
      trigger,
      triggerId,
    });
    const [response] = await operation.promise();

    console.log(`Created trigger: ${response.name}`);
    return response;
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Trigger ${triggerId} already exists: ${err.message}`);
    } else if (err.code === status.NOT_FOUND) {
      console.error(`Resource not found: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else {
      console.error(`Failed to create trigger: ${err.message}`);
    }
    throw err;
  }
}

module.exports = { createTrigger };

Python

To authenticate to Eventarc, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import google.api_core.exceptions
from google.cloud import eventarc_v1


def create_trigger(
    trigger_id: str,
    project_id: str,
    location_id: str,
    destination_run_service_id: str,
) -> None:
    """Create an Eventarc trigger.

    Args:
        trigger_id: The unique identifier for the trigger (for example, 'example-trigger').
        project_id: The Google Cloud project ID.
        location_id: The Google Cloud region for the trigger (for example, 'us-central1').
        destination_run_service_id: The name of the destination Cloud Run service receiving events (for example, 'example-service').
    """
    client = eventarc_v1.EventarcClient()

    parent = f"projects/{project_id}/locations/{location_id}"
    trigger = eventarc_v1.Trigger(
        name=f"{parent}/triggers/{trigger_id}",
        event_filters=[
            eventarc_v1.EventFilter(
                attribute="type",
                value="google.cloud.pubsub.topic.v1.messagePublished",
            )
        ],
        destination=eventarc_v1.Destination(
            cloud_run=eventarc_v1.CloudRun(
                service=destination_run_service_id,
                region=location_id,
            )
        ),
    )

    try:
        operation = client.create_trigger(
            parent=parent,
            trigger=trigger,
            trigger_id=trigger_id,
        )
        response = operation.result()
        print(f"Created trigger: {response.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Failed to create trigger: {error}")

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.