Trigger Cloud Run with events from Eventarc

6a5cf23c8e20491f.png

Cloud Run allows you to run stateless containers in a fully managed environment. It is built from open-source Knative, letting you choose to run your containers either fully managed with Cloud Run, or in your Google Kubernetes Engine cluster with Cloud Run for Anthos.

Eventarc makes it easy to connect Cloud Run services with events from a variety of sources. It allows you to build event-driven architectures in which microservices are loosely coupled and distributed. It also takes care of event ingestion, delivery, security, authorization, and error-handling for you which improves developer agility and application resilience.

In this codelab, you will learn about Eventarc. More specifically, you will listen to events from Cloud Pub/Sub and Cloud Audit Logs with Eventarc and pass them to Cloud Run.

What you'll learn

  • Long term vision of Eventarc
  • Current state of Eventarc
  • Create a Cloud Run sink
  • Create an Event trigger for Cloud Pub/Sub
  • Create an Event trigger for Cloud Audit Logs

Long-term Vision is to be able to deliver events from various sources to Google Cloud sinks and Custom sinks.

5480b3d19596f0.png

Google Cloud sources

Event sources that are Google Cloud owned products

Google sources

Event sources that are Google-owned products such as Gmail, Hangouts, Android Management and more

Custom sources

Event sources that are not Google-owned products and are created by end-users themselves

3rd party sources

Event sources that are neither Google-owned nor customer-produced. This includes popular event sources such as Github, SAP, Datadog, Pagerduty, etc that are owned and maintained by 3rd party providers, partners, or OSS communities.

Events are normalized to CloudEvents v1.0 format for cross-service interoperability. CloudEvents is a vendor-neutral open spec describing event data in common formats, enabling interoperability across services, platforms and systems.

This preview is the first version which delivers an initial set of the long-term functionality.

4621ff9603687968.png

You can draw events from Google Cloud sources and Custom applications publishing to Cloud Pub/Sub and deliver them to Google Cloud Run sinks.

Events from a breadth of Google Cloud sources are delivered by way of Cloud Audit Logs. The latency and availability of event delivery from these sources are tied to those of Cloud Audit Logs. Whenever an event from a Google Cloud source is fired, a corresponding Cloud Audit Log entry is created.

Custom applications publishing to Cloud Pub/Sub can publish messages to a Pub/Sub topic they specify and in any format.

The underlying delivery mechanism in Eventarc is Cloud Pub/Sub and topics and subscriptions created to facilitate event delivery are visible in customers' Pub/Sub instance for their project.

Event triggers are the filtering mechanism to specify which events to deliver to which sink.

All events are delivered in the Cloud Events v1.0 format for cross service interoperability.

Self-paced environment setup

  1. Sign in to Cloud Console and create a new project or reuse an existing one. (If you don't already have a Gmail or G Suite account, you must create one.)

H_hgylo4zxOllHaAbPKJ7VyqCKPDUnDhkr-BsBIFBsrB6TYSisg6LX-uqmMhh4sXUy_hoa2Qv87C2nFmkg-QAcCiZZp0qtpf6VPaNEEfP_iqt29KVLD-gklBWugQVeOWsFnJmNjHDw

dcCPqfBIwNO4R-0fNQLUC4aYXOOZhKhjUnakFLZJGeziw2ikOxGjGkCHDwN5x5kCbPFB8fiOzZnX-GfuzQ8Ox-UU15BwHirkVPR_0RJwl0oXrhqZmMIvZMa_uwHugBJIdx5-bZ6Z8Q

jgLzVCxk93d6E2bbonzATKA4jFZReoQ-fORxZZLEi5C3D-ubnv6nL-eP-iyh7qAsWyq_nyzzuEoPFD1wFOFZOe4FWhPBJjUDncnTxTImT3Ts9TM54f4nPpsAp52O0y3Cb19IceAEgQ

Remember the project ID, a unique name across all Google Cloud projects (the name above has already been taken and will not work for you, sorry!). It will be referred to later in this codelab as PROJECT_ID.

  1. Next, you'll need to enable billing in Cloud Console in order to use Google Cloud resources.

Running through this codelab shouldn't cost much, if anything at all. Be sure to to follow any instructions in the "Cleaning up" section which advises you how to shut down resources so you don't incur billing beyond this tutorial. New users of Google Cloud are eligible for the $300USD Free Trial program.

Start Cloud Shell

While Google Cloud can be operated remotely from your laptop, in this codelab you will be using Google Cloud Shell, a command line environment running in the Cloud.

From the GCP Console click the Cloud Shell icon on the top right toolbar:

STgwiN06Y0s_gL7i9bTed8duc9tWOIaFw0z_4QOjc-jeOmuH2TBK8l4udei56CKPLoM_i1yEF6pn5Ga88eniJQoEh8cAiTH79gWUHJdKOw0oiBZfBpOdcEOl6p29i4mvPe_A6UMJBQ

It should only take a few moments to provision and connect to the environment. When it is finished, you should see something like this:

r6WRHJDzL-GdB5VDxMWa67_cQxRR_x_xCG5xdt9Nilfuwe9fTGAwM9XSZbNPWvDSFtrZ7DDecKqR5_pIq2IJJ9puAMkC3Kt4JbN9jfMX3gAwTNHNqFmqOJ-3iIX5HSePO4dNVZUkNA

This virtual machine is loaded with all the development tools you'll need. It offers a persistent 5GB home directory, and runs on Google Cloud, greatly enhancing network performance and authentication. All of your work in this lab can be done with simply a browser.

Enable APIs

Inside Cloud Shell, make sure that you project id is setup:

gcloud config set project [YOUR-PROJECT-ID]

Check that the gcloud component for beta is installed:

gcloud components install beta

Enable all necessary services:

gcloud services enable run.googleapis.com
gcloud services enable eventarc.googleapis.com
gcloud services enable logging.googleapis.com
gcloud services enable cloudbuild.googleapis.com

You also need to enable Data Access Audit Logs (Admin read, Data read, Data write) for all Google Cloud services from which you intend to receive events. In a later step, we will show you how to enable audit logs for Google Cloud Storage.

Set region and platform

Eventarc is currently available in the following GCP regions: us-central1, us-east1, asia-east1, europe-west1 and global.

In Cloud Shell, set the Cloud Run region to one of the supported regions, platform to managed and the location of Eventarc trigger:

export REGION=europe-west1
gcloud config set run/region ${REGION}
gcloud config set run/platform managed
gcloud config set eventarc/location ${REGION}

You can check that the configuration is set:

gcloud config list

...
[eventarc]
location = europe-west1
...
[run]
platform = managed
region = europe-west1

Configure service accounts

Configure a couple of service accounts needed for the Audit Log trigger.

Grant the iam.serviceAccountTokenCreator role to the Pub/Sub service account:

export PROJECT_NUMBER="$(gcloud projects list --filter=$(gcloud config get-value project) --format='value(PROJECT_NUMBER)')"

gcloud projects add-iam-policy-binding $(gcloud config get-value project) \
    --member="serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-pubsub.iam.gserviceaccount.com"\
    --role='roles/iam.serviceAccountTokenCreator'

Grant the eventarc.admin role to the default Compute Engine service account:

gcloud projects add-iam-policy-binding $(gcloud config get-value project) \
    --member=serviceAccount:${PROJECT_NUMBER}-compute@developer.gserviceaccount.com \
    --role='roles/eventarc.admin'

You can discover what the registered sources are, the types of events they can emit, and how to configure triggers in order to consume them.

To see the list of different types of events:

gcloud beta eventarc attributes types list

NAME                                           DESCRIPTION
google.cloud.audit.log.v1.written              Cloud Audit Log written
google.cloud.pubsub.topic.v1.messagePublished  Cloud Pub/Sub message published

To get more information about each event type:

gcloud beta eventarc attributes types describe google.cloud.pubsub.topic.v1.messagePublished

As an event sink, deploy a Cloud Run service that logs the contents of the CloudEvent it receives.

You can use Knative's event_display that is already compiled and its container image built as part of Knative release. You can see the container image details in event-display.yaml:

...
containers:
  - image: gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display@sha256:8da2440b62a5c077d9882ed50397730e84d07037b1c8a3e40ff6b89c37332b27

Deploy to Cloud Run

Deploy your containerized application to Cloud Run:

export SERVICE_NAME=event-display
gcloud run deploy ${SERVICE_NAME} \
  --image gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display@sha256:8da2440b62a5c077d9882ed50397730e84d07037b1c8a3e40ff6b89c37332b27 \
  --allow-unauthenticated

On success, the command line displays the service URL. You can now visit your deployed container by opening the service URL in any browser window.

One way of receiving events is through Cloud Pub/Sub. Custom applications can publish messages to Cloud Pub/Sub and these messages can be delivered to Google Cloud Run sinks via Eventarc.

Create a trigger

Before creating the trigger, get more details on the parameters you'll need to construct a trigger for events from Cloud Pub/Sub:

gcloud beta eventarc attributes types describe google.cloud.pubsub.topic.v1.messagePublished

Create a trigger to filter events published to the Cloud Pub/Sub topic to our deployed Cloud Run service:

gcloud beta eventarc triggers create trigger-pubsub \
  --destination-run-service=${SERVICE_NAME} \
  --destination-run-region=${REGION}
  --matching-criteria="type=google.cloud.pubsub.topic.v1.messagePublished"

Find the topic

Pub/Sub trigger creates a Pub/Sub topic under the covers. Let's find it out and assign to a variable:

export TOPIC_ID=$(gcloud beta eventarc triggers describe trigger-pubsub --format='value(transport.pubsub.topic)')

Test the trigger

You can check that the trigger is created by listing all triggers:

gcloud beta eventarc triggers list

You might need to wait for up to 10 minutes for the trigger creation to be propagated and for it to begin filtering events.

In order to simulate a custom application sending message, you can use gcloud to to fire an event:

gcloud pubsub topics publish ${TOPIC_ID} --message="Hello there"

The Cloud Run sink we created logs the body of the incoming message. You can view this in the Logs section of your Cloud Run instance:

a0f3ec83e6294419.png

Note that "Hello there" will be base64 encoded as it was sent by Pub/Sub and you will have to decode it if you want to see the original message sent.

Delete the trigger

Optionally, you can delete the trigger once done testing.

gcloud beta eventarc triggers delete trigger-pubsub

You will set up a trigger to listen for events from Cloud Audit Logs. More specifically, you will look for Cloud Storage events in Cloud Audit Logs.

Create a bucket

First, create a Cloud Storage bucket in the same region as the deployed Cloud Run service. You can replace BUCKET_NAME with a unique name you prefer:

export BUCKET_NAME=cr-bucket-$(gcloud config get-value project)
gsutil mb -p $(gcloud config get-value project) \
  -l $(gcloud config get-value run/region) \
  gs://${BUCKET_NAME}/

Enable Cloud Audit Logs

In order to receive events from a service, you need to enable Cloud Audit Logs. From the Cloud Console, select IAM & Admin and Audit Logs from the upper left-hand menu. In the list of services, check Google Cloud Storage:

3053afc271d2734c.png

On the right hand side, make sure Admin, Read and Write are selected. Click save:

bec31b4f35fbcea.png

Test Cloud Audit Logs

To learn how to identify the parameters you'll need to set up an actual trigger, perform an actual operation.

For example, create a random text file and upload it to the bucket:

echo "Hello World" > random.txt
gsutil cp random.txt gs://${BUCKET_NAME}/random.txt

Now, let's see what kind of audit log this update generated. From the Cloud Console, select Logging and Logs Viewer from the upper left-hand menu.

Under Query Builder, choose GCS Bucket and choose your bucket and its location. Click Add.

db831de1a42ea560.png

Once you run the query, you'll see logs for the storage bucket and one of those should be storage.objects.create:

df57e9799dde5b8.png

Note the serviceName, methodName and resourceName. We'll use these in creating the trigger.

Create a trigger

You are now ready to create an event trigger for Cloud Audit Logs.

You can get more details on the parameters you'll need to construct the trigger:

gcloud beta eventarc attributes types describe google.cloud.audit.log.v1.written

Create the trigger with the right filters and the service account:

gcloud beta eventarc triggers create trigger-auditlog \
  --destination-run-service=${SERVICE_NAME} \
  --destination-run-region=${REGION}
  --matching-criteria="type=google.cloud.audit.log.v1.written" \
  --matching-criteria="serviceName=storage.googleapis.com" \
  --matching-criteria="methodName=storage.objects.create" \
  --service-account=${PROJECT_NUMBER}-compute@developer.gserviceaccount.com

Test the trigger

List all triggers to confirm that trigger was successfully created:

gcloud beta eventarc triggers list

Wait for up to 10 minutes for the trigger creation to be propagated and for it to begin filtering events. Once ready, it will filter create events and send them to the service.

You're now ready to fire an event.

Upload the same file to the Cloud Storage bucket as you did earlier:

gsutil cp random.txt gs://${BUCKET_NAME}/random.txt

If you check the logs of the Cloud Run service in Cloud Console, you should see the received event:

aff3b2e7ad05c75d.png

Delete the trigger

Optionally, you can delete the trigger once done testing:

gcloud beta eventarc triggers delete trigger-auditlog

Congratulations for completing the codelab.

What we've covered

  • Long term vision of Eventarc
  • Current state of Eventarc
  • Create a Cloud Run sink
  • Create an Event trigger for Cloud Pub/Sub
  • Create an Event trigger for Cloud Audit Logs