This tutorial demonstrates writing, deploying, and triggering an event-driven Cloud Run function with a Cloud Audit Logs trigger.
Cloud Run functions enables your functions to be triggered by Cloud Audit Logs entries. Many Google Cloud products write to Cloud Audit Logs when important in-product actions occur. These log entries can trigger the execution of Cloud Run functions in real time, which allows users to automatically process and/or act on them.
These logs are generated by many different events in Google Cloud and cover most Google Cloud products. Thus, Cloud Audit Logs triggers enable you to create functions that react to most state changes in Google Cloud.
This tutorial will show you how use Cloud Audit Logs triggers to label newly created Compute Engine instances with the name of the entity (person or service account) that created them.
If you are new to Cloud Audit Logs and want to learn more, see the Cloud Audit Logs documentation.
Objectives
- Write an event-driven Cloud Run function that receives a Cloud Audit Logs event when a Compute Engine VM instance is created.
- Trigger the function by creating a Compute Engine VM instance, at which point the instance will be labeled with the name of the entity (person or service account) that created it.
Costs
In this document, you use the following billable components of Google Cloud:
- Cloud Run functions
- Cloud Build
- Pub/Sub
- Artifact Registry
- Eventarc
- Cloud Logging
- Compute Engine
For details, see Cloud Run functions pricing.
To generate a cost estimate based on your projected usage,
use the pricing calculator.
Before you begin
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions, Cloud Run, Cloud Build, Artifact Registry, Eventarc, Logging, Compute Engine, and Pub/Sub APIs.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions, Cloud Run, Cloud Build, Artifact Registry, Eventarc, Logging, Compute Engine, and Pub/Sub APIs.
- Install and initialize the Cloud SDK.
- Update
gcloud
components: - Prepare your development environment.
gcloud components update
Need a command prompt? You can use the Google Cloud Shell. The Google Cloud Shell is a command line environment that already includes the Google Cloud SDK, so you don't need to install it. The Google Cloud SDK also comes preinstalled on Compute Engine Virtual Machines.
Prerequisites
Open the IAM & Admin > Audit Logs page in the Google Cloud console:
Enable the Cloud Audit Logs Admin Read, Data Read, and Data Write Log Types for the Compute Engine API:
Check whether the Compute Engine Service Account has the
Editor
role. This service account will be used as the service identity for Cloud Run functions.Go to the IAM & Admin > IAM page
Find the entry
PROJECT_NUMBER-compute@developer.gserviceaccount.com
in the table and look at theRoles
column. If the column containsEditor
you can skip the following steps. Otherwise, go to the next steps and assign the necessary roles to the service account.Grant the
eventarc.eventReceiver
role to the project's Compute Engine service account:PROJECT_ID=$(gcloud config get-value project) PROJECT_NUMBER=$(gcloud projects list --filter="project_id:$PROJECT_ID" --format='value(project_number)') # Allow service account token creation gcloud projects add-iam-policy-binding $PROJECT_ID \ --member serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com \ --role roles/eventarc.eventReceiver
Grant the
run.invoker
role to the project's Compute Engine service account so that the Pub/Sub trigger can execute the function:PROJECT_ID=$(gcloud config get-value project) PROJECT_NUMBER=$(gcloud projects list --filter="project_id:$PROJECT_ID" --format='value(project_number)') # Allow service account token creation gcloud projects add-iam-policy-binding $PROJECT_ID \ --member serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com \ --role roles/run.invoker
Grant the
compute.instanceAdmin
role to the project's Compute Engine service account so that the function code has the necessary permissions to get VM instances and set labels on them:PROJECT_ID=$(gcloud config get-value project) PROJECT_NUMBER=$(gcloud projects list --filter="project_id:$PROJECT_ID" --format='value(project_number)') # Allow service account token creation gcloud projects add-iam-policy-binding $PROJECT_ID \ --member serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com \ --role roles/compute.instanceAdmin
Preparing the application
Clone the sample app repository to your local machine:
Node.js
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git
Alternatively, you can download the sample as a zip file and extract it.
Python
git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
Alternatively, you can download the sample as a zip file and extract it.
Go
git clone https://github.com/GoogleCloudPlatform/golang-samples.git
Alternatively, you can download the sample as a zip file and extract it.
Java
git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
Alternatively, you can download the sample as a zip file and extract it.
Change to the directory that contains the Cloud Run functions sample code for accessing Cloud Audit Logs:
Node.js
cd nodejs-docs-samples/functions/v2/autoLabelInstance/
Python
cd python-docs-samples/functions/v2/label_gce_instance/
Go
cd golang-samples/functions/functionsv2/label_gce_instance/
Java
cd java-docs-samples/functions/v2/label-compute-instance/
Take a look at the sample code:
Node.js
Python
Go
Java
Deploying the function
To deploy the function with a Cloud Audit Logs trigger, run the following command
in the directory that contains the sample code (or in the case of Java, the
pom.xml
file):
Node.js
gcloud functions deploy nodejs-cal-function \ --gen2 \ --runtime=nodejs20 \ --region=REGION
\ --source=. \ --entry-point=autoLabelInstance \
--trigger-location=REGION
\
--trigger-event-filters="type=google.cloud.audit.log.v1.written" \
--trigger-event-filters="serviceName=compute.googleapis.com" \
--trigger-event-filters="methodName=v1.compute.instances.insert"
Use the --runtime
flag to specify the runtime ID of a
supported Node.js version to run
your function.
Python
gcloud functions deploy python-cal-function \ --gen2 \ --runtime=python312 \ --region=REGION
\ --source=. \ --entry-point=label_gce_instance \
--trigger-location=REGION
\
--trigger-event-filters="type=google.cloud.audit.log.v1.written" \
--trigger-event-filters="serviceName=compute.googleapis.com" \
--trigger-event-filters="methodName=v1.compute.instances.insert"
Use the --runtime
flag to specify the runtime ID of a
supported Python version to run
your function.
Go
gcloud functions deploy go-cal-function \ --gen2 \ --runtime=go121 \ --region=REGION
\ --source=. \ --entry-point=label-gce-instance \
--trigger-location=REGION
\
--trigger-event-filters="type=google.cloud.audit.log.v1.written" \
--trigger-event-filters="serviceName=compute.googleapis.com" \
--trigger-event-filters="methodName=v1.compute.instances.insert"
Use the --runtime
flag to specify the runtime ID of a
supported Go version to run
your function.
Java
gcloud functions deploy java-cal-function \ --gen2 \ --runtime=java17 \ --region=REGION
\ --source=. \ --entry-point=functions.AutoLabelInstance \ --memory=512MB \
--trigger-location=REGION
\
--trigger-event-filters="type=google.cloud.audit.log.v1.written" \
--trigger-event-filters="serviceName=compute.googleapis.com" \
--trigger-event-filters="methodName=v1.compute.instances.insert"
Use the --runtime
flag to specify the runtime ID of a
supported Java version to run
your function.
The deployment command above specifies the following event filter parameters that correspond to VM creation:
type
: The Cloud Audit Logs event type (google.cloud.audit.log.v1.written
).serviceName
: The name of the Google Cloud service that generated the log entry, in this casecompute.googleapis.com
.methodName
: The name of the API method that generated the log entry, in this casev1.compute.instances.insert
.
Triggering the function
Once the function is deployed, you can confirm that it works:
Create a Compute Engine VM instance:
gcloud compute instances create
YOUR_INSTANCE_NAME
--zoneYOUR_ZONE
Alternatively, go to the Google Cloud console and click Create a VM.
Run the following command to verify that the instance has been labeled appropriately:
gcloud compute instances describe
YOUR_INSTANCE_NAME
\ --zoneYOUR_ZONE \ --format 'value(labels)'
You should see a label with the format
creator=YOURNAMEYOUR_DOMAIN
.
Clean up
To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.
Deleting the project
The easiest way to eliminate billing is to delete the project that you created for the tutorial.
To delete the project:
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
Deleting the function
Deleting Cloud Run functions does not remove any resources stored in Cloud Storage.
To delete the Cloud Run function you created in this tutorial, run the following command:
Node.js
gcloud functions delete nodejs-cal-function --gen2 --region REGION
Python
gcloud functions delete python-cal-function --gen2 --region REGION
Go
gcloud functions delete go-cal-function --gen2 --region REGION
Java
gcloud functions delete java-cal-function --gen2 --region REGION
You can also delete Cloud Run functions from the Google Cloud console.
Deleting the Compute Engine VM instance
To delete the Compute Engine VM instance you created in this tutorial, run the following command:
gcloud compute instances deleteYOUR_INSTANCE_NAME
--zoneYOUR_ZONE