Create a new Eventarc enrollment to route events from a message bus to a destination.

## Code sample

### Java


To authenticate to Eventarc, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```java
import com.google.cloud.eventarc.v1.Enrollment;
import com.google.cloud.eventarc.v1.EventarcClient;
import com.google.cloud.eventarc.v1.LocationName;

public class CreateEnrollment {

  public static void main(String[] args) throws Exception {
    String enrollmentId = "example-enrollment-id";
    String projectId = "example-project-id";
    String locationId = "us-central1";
    String messageBusId = "example-message-bus-id";
    createEnrollment(enrollmentId, projectId, locationId, messageBusId);
  }

  public static void createEnrollment(
      String enrollmentId, String projectId, String locationId, String messageBusId)
      throws Exception {
    try (EventarcClient client = EventarcClient.create()) {
      String parent = LocationName.of(projectId, locationId).toString();
      String messageBus =
          String.format("projects/%s/locations/%s/messageBuses/%s", projectId, locationId, messageBusId);
      String destination =
          String.format("projects/%s/locations/%s/pipelines/example-pipeline", projectId, locationId);

      Enrollment enrollment =
          Enrollment.newBuilder()
              .setMessageBus(messageBus)
              .setCelMatch("message.type == 'google.cloud.pubsub.topic.v1.messagePublished'")
              .setDestination(destination)
              .build();

      Enrollment response = client.createEnrollmentAsync(parent, enrollment, enrollmentId).get();
      System.out.println("Created enrollment: " + 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](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```javascript
'use strict';

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

const client = new EventarcClient();

/**
 * Creates an Eventarc enrollment.
 *
 * @param {string} enrollmentId - Caller-chosen ID to assign to the Enrollment. Must match '^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$' (for example, 'example-enrollment').
 * @param {string} projectId - Google Cloud project ID (for example, 'example-project').
 * @param {string} locationId - Google Cloud location or region (for example, 'us-central1').
 * @param {string} messageBusId - Resource ID of the prerequisite MessageBus to subscribe to (for example, 'example-message-bus'). Sourced from an existing MessageBus.
 */
async function createEnrollment(enrollmentId, projectId, locationId, messageBusId) {
  try {
    const parent = `projects/${projectId}/locations/${locationId}`;
    const enrollment = {
      celMatch: 'message.type == "google.cloud.pubsub.topic.v1.messagePublished"',
      messageBus: `projects/${projectId}/locations/${locationId}/messageBuses/${messageBusId}`,
      destination: `projects/${projectId}/locations/${locationId}/pipelines/example-pipeline`,
    };

    const [operation] = await client.createEnrollment({
      parent,
      enrollment,
      enrollmentId,
    });
    const [response] = await operation.promise();

    console.log(`Created enrollment: ${response.name}`);
    return response;
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Enrollment already exists: ${err.message}`);
    } else if (err.code === status.NOT_FOUND) {
      console.error(`Resource not found: ${err.message}`);
    } else if (err.code) {
      console.error(`Google API error code ${err.code}: ${err.message}`);
    } else {
      throw err;
    }
  }
}

module.exports = { createEnrollment };
```

### Python


To authenticate to Eventarc, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

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

client = eventarc_v1.EventarcClient()


def create_enrollment(
    enrollment_id: str, project_id: str, location_id: str, message_bus_id: str
) -> None:
    """Use the create_enrollment method

    Args:
        enrollment_id: The user-provided ID to be assigned to the Enrollment.
        project_id: The Google Cloud project ID.
        location_id: The Google Cloud region or location ID (for example, 'us-central1').
        message_bus_id: The ID of the MessageBus to subscribe to.
    """
    parent = f"projects/{project_id}/locations/{location_id}"
    message_bus_path = (
        f"projects/{project_id}/locations/{location_id}/messageBuses/{message_bus_id}"
    )
    destination_pipeline = (
        f"projects/{project_id}/locations/{location_id}/pipelines/example-pipeline"
    )

    enrollment = eventarc_v1.Enrollment(
        cel_match='message.type == "google.cloud.pubsub.topic.v1.messagePublished"',
        message_bus=message_bus_path,
        destination=destination_pipeline,
    )

    try:
        operation = client.create_enrollment(
            parent=parent,
            enrollment=enrollment,
            enrollment_id=enrollment_id,
        )
        response = operation.result()
        print(f"Created enrollment: {response.name}")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"Failed to create enrollment: {e}")
```

## What's next


To search and filter code samples for other Google Cloud products, see the
[Google Cloud sample browser](https://docs.cloud.google.com/docs/samples.md.txt?product=eventarc).