Serverless computing on Google Cloud lets you develop and deploy highly scalable applications on a fully managed serverless platform. Services are automatically scaled up and down depending on traffic.
Eventarc lets you build event-driven architectures without having to implement, customize, or maintain the underlying infrastructure. Eventarc offers a standardized solution to manage the flow of state changes, called events, between decoupled services.
An Eventarc trigger is a declaration that a specific destination service is interested in a chosen event from an event provider. Eventarc manages the routing and delivery of events to the destination service.
In this lab, you create a trigger that sends an event when a message is sent to a Pub/Sub topic. You create a second trigger that sends an event when an IAMservice account is created.
Note: Read these instructions.
Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.
This Qwiklabs hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.
What you need
To complete this lab, you need:
Access to a standard internet browser (Chrome browser recommended).
Time to complete the lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab.Note: If you are using a Pixelbook, open an Incognito window to run this lab.
How to start your lab and sign in to the Console
Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method.
On the left is a panel populated with the temporary credentials that you must use for this lab.
Copy the username, and then click Open Google Console.
The lab spins up resources, and then opens another tab that shows the Choose an account page.
Note: Open the tabs in separate windows, side-by-side.
On the Choose an account page, click Use Another Account. The Sign in page opens.
Paste the username that you copied from the Connection Details panel. Then copy and paste the password.
Note: You must use the credentials from the Connection Details panel. Do not use your Google Cloud Skills Boost credentials. If you have your own Google Cloud account, do not use it for this lab (avoids incurring charges).
Click through the subsequent pages:
Accept the terms and conditions.
Do not add recovery options or two-factor authentication (because this is a temporary account).
Do not sign up for free trials.
After a few moments, the Cloud console opens in this tab.
Note: You can view the menu with a list of Google Cloud Products and Services by clicking the Navigation menu at the top-left.
Activate Google Cloud Shell
Google Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud.
Google Cloud Shell provides command-line access to your Google Cloud resources.
In Cloud console, on the top right toolbar, click the Open Cloud Shell button.
Click Continue.
It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. For example:
gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.
You can list the active account name with this command:
This application uses several Google Cloud services, and you must enable each of the APIs for these services.
The APIs being enabled are:
The Pub/Sub API manages Pub/Sub topics and subscriptions and publishes Pub/Sub messages. Pub/Sub is used to manage the event transport in Eventarc. In this lab, a Pub/Sub topic is be used by Eventarc to generate events when messages are published to the topic.
The Cloud Logging API writes log entries and manages Cloud Logging configuration. Cloud Logging log entries are used by Eventarc to generate many types of events, including IAM events.
The Eventarc API manages Eventarc configuration. In this lab, Eventarc is used to create triggers that deliver events to the event destination service.
The Cloud Run API creates and manages Cloud Run services. In this lab, a Cloud Run service logs the event data delivered by Eventarc.
Build and deploy the eventarc-event-logger service
The Eventarc event logger service logs an incoming HTTP request. The log entries created by this service will be used to explore the contents of the Eventarc event request.
In Cloud Shell, click Open Editor.
Click Open in new window.
Note:
It may take a minute or two until the Open in new window link appears. After opening the editor, you can ignore or close the error message boxes that are displayed.
The editor will open in a new tab.
In the previous tab, click Open Terminal to reopen Cloud Shell.
Return to the Cloud Editor tab, navigate to ~/eventarc-event-logger, and then examine the files for the eventarc-event-logger service.
The directory contains three files:
package.json holds metadata relevant to building the Node.js service. It defines the command that starts the application (node index.js) and specifies the versions of packages used by the code.
Dockerfile specifies the starting image (node:18-slim) and contains the list of commands that are run to build the container image that will host our service.
index.js contains the code for the service.
To build the Docker image of the eventarc-event-logger service, in Cloud Shell, run the following command:
By leaving the Pub/Sub topic set to None, you have indicated that Eventarc should automatically create and manage the Pub/Sub topic for this trigger. If your Eventarc trigger is deleted, the corresponding Pub/Sub topic will also be automatically deleted.
On the same page, select Service account > Create New Service Account.
On the Create new service account pane, set the Service account name to pubsub-trigger-sa and then click Create.
Click Done.
If you're notified that Pub/Sub needs the role roles/iam.serviceAccountTokenCreator granted to the Pub/Sub service account, click Grant.
You can also add the role by running the following command in Cloud Shell:
Log entries from the eventarc-event-logger service are shown here. You should see that the service has been deployed, but there are no events logged yet.
The gcloud pubsub topics publish command sends a message with attached attributes to the topic.
On the Logs page for eventarc-event-logger, drag the scroll bar to search for newer entries in the log.
The log entries for the eventarc-event-logger service are shown, but the Pub/Sub event has not been logged!
Instead, you will see one or more POST 403 entries.
Expand one of the POST 403 entries.
The textPayload field in the log shows an error that looks like this:
The request was not authenticated. Either allow unauthenticated invocations or set the proper Authorization header. Read more at https://cloud.google.com/run/docs/securing/authenticating Additional troubleshooting documentation can be found at: https://cloud.google.com/run/docs/troubleshooting#unauthorized-client
The error message indicates that you can solve the problem by allowing unauthenticated invocations. It is not a best practice to allow unauthenticated calls to your event receivers.
The HTTP request from Eventarc was unauthorized. Do you know why that might be?
Fix the service account permissions
The eventarc-event-logger service is being called, but the error indicates that the service account can't call the Cloud Run service.
Follow the principle of least privilege when creating service accounts. The service account should only be able to access services necessary for the specific trigger.
To give the service account permission to call the Cloud Run service, in Cloud Shell, run the following commands:
Drag the scrollbar on the Logs page for eventarc-event-logger until you see a successful event.
Note:
It may take a minute before the log entry appears.
When the service successfully receives the event, it logs EVENT RECEIVED (google.cloud.pubsub.topic.v1.messagePublished). This log entry shows the event type that was delivered in the ce-type header.
Examine the logged event
Expand the log entry that follows the HEADERS (EXCEPT AUTH) entry, and then expand the jsonPayload object.
The jsonPayload object contains the headers that were received with the request. Important headers include:
Headers starting with ce- are CloudEvents standard headers.
ce-id is the Pub/Sub message ID of the message you delivered to the topic. The message ID is used as the CloudEvents ID for Pub/Sub messaging triggers.
ce-type is the event type of the received event.
ce-source is the URI for the topic.
ce-time indicates the time the Pub/Sub message was received by the topic.
content-type specifies the type of the body. In this case, the header indicates that the body contains JSON.
Expand the log entry that follows the BODY entry, and then expand the jsonPayload object.
The jsonPayload object in this entry contains the Pub/Sub event. The JSON for this object resembles this:
To let the service account invoke the eventarc-event-logger service, run the following command:
export SERVICE_REGION={{{ project_0.default_region | REGION_PLACEHOLDER }}}
gcloud run services add-iam-policy-binding eventarc-event-logger \
--region=${SERVICE_REGION} \
--member=serviceAccount:svcacct-create-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com \
--role="roles/run.invoker"
Note:
It may take a minute for the run.invoker role to be reflected when you check your progress.
Click Check my progress to verify the objective.
Create the service account for the Audit Logs trigger
Task 5. Create an Audit Logs trigger
In this task, you create and test a trigger that delivers an event when a log entry indicates that a service account was created.
Create the trigger
In the Google Cloud console, navigate to Cloud Run, and then click on eventarc-event-logger service.
On the Service details page, navigate to the Triggers tab.
Click + Add Triggers and select Other Eventarc trigger from the dropdown.
In the Eventarc trigger window, specify the following:
Property
Value
Trigger name
svcacct-create-trigger
Trigger type
selectGoogle sources
Event provider
selectCloud IAM
Event type
selectgoogle.iam.admin.v1.CreateServiceAccount
Resource
selectAny resource
Region
select
Service account
select the svcacct-create-sa service account
Note:
You may see a warning that some Data Access audit logs are disabled for IAM. Data Access logs are used when someone retrieves information about an entity. In this case, your event occurs when a service account is created, not just accessed. Logging of service account creation is enabled by default, so you don't need to enable Data Access logging.
By selecting Any resource, you will get an event for each service account created for this project.
Click Save Trigger.
After the trigger has been created, you're automatically taken to the Service details page.
On the Service details page, click the Logs tab.
You should only see google.cloud.pubsub.topic.v1.messagePublished logs. The generation of IAM service account creation events started when the trigger was created. Service accounts you created before the trigger will not result in events.
Create a service account
To create a new service account, in Cloud Shell, run the following command:
gcloud iam service-accounts create test-sa --display-name="Test service account"
Drag the scrollbar on the Logs page for eventarc-event-logger until you see a successful audit log event.
You should see an EVENT RECEIVED (google.cloud.audit.log.v1.written) log entry. All events that are generated by Cloud Audit Logs entries use the google.cloud.audit.log.v1.written event type.
Examine the logged event
Expand the log entry that follows the latest HEADERS (EXCEPT AUTH) entry, and then expand the jsonPayload object.
The jsonPayload object contains the headers that were received with the request. Important headers include:
Headers starting with ce- are CloudEvents standard headers.
ce-id specifies the unique CloudEvents ID for the event.
ce-type is the event type of the received event. For Cloud Audit Logs events, the type is always google.cloud.audit.log.v1.written.
ce-servicename specifies the service that created the audit log entry.
ce-methodname specifies the log entry type. For this example, the method name is the Event that you selected when creating the trigger.
ce-time indicates the time that the audit log entry was created.
ce-recordedtime indicates the time that the actual event occurred, according to the originating service. For this event, the recorded time is the time when the service account was created.
Expand the log entry that follows the latest BODY entry, and then expand the jsonPayload object.
The jsonPayload object contains the IAM event. The JSON for the object looks similar to this:
You can see the details of the service account creation in the request and response objects. The log entry shows the details of the API call made by the gcloud CLI command.
Click Check my progress to verify the objective.
Create an Audit Logs trigger
Congratulations!
In this lab, you enabled required APIs and built and deployed a Cloud Run service that logs delivered events. You created an Eventarc trigger that generated an event when a message was sent to a Pub/Sub topic. You created another trigger that sent an event when an IAM service account was created.
Next Steps / Learn More
For more information about Eventarc, view these links:
Copyright 2023 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.
Los labs crean un proyecto de Google Cloud y recursos por un tiempo determinado
.
Los labs tienen un límite de tiempo y no tienen la función de pausa. Si finalizas el lab, deberás reiniciarlo desde el principio.
En la parte superior izquierda de la pantalla, haz clic en Comenzar lab para empezar
Usa la navegación privada
Copia el nombre de usuario y la contraseña proporcionados para el lab
Haz clic en Abrir la consola en modo privado
Accede a la consola
Accede con tus credenciales del lab. Si usas otras credenciales, se generarán errores o se incurrirá en cargos.
Acepta las condiciones y omite la página de recursos de recuperación
No hagas clic en Finalizar lab, a menos que lo hayas terminado o quieras reiniciarlo, ya que se borrará tu trabajo y se quitará el proyecto
Este contenido no está disponible en este momento
Te enviaremos una notificación por correo electrónico cuando esté disponible
¡Genial!
Nos comunicaremos contigo por correo electrónico si está disponible
Un lab a la vez
Confirma para finalizar todos los labs existentes y comenzar este
Usa la navegación privada para ejecutar el lab
Usa una ventana de navegación privada o de Incógnito para ejecutar el lab. Así
evitarás cualquier conflicto entre tu cuenta personal y la cuenta
de estudiante, lo que podría generar cargos adicionales en tu cuenta personal.
In this lab, you create an Eventarc trigger that sends an event when a message is sent to a Pub/Sub topic. You create a second trigger that sends an event when a service account is created or deleted.
Duración:
0 min de configuración
·
Acceso por 60 min
·
60 min para completar