Cloud Storage Tutorial (2nd gen)

This simple tutorial demonstrates writing, deploying, and triggering an Event-Driven Cloud Function with a Cloud Storage trigger to respond to Cloud Storage events.

If you're looking for code samples for using Cloud Storage itself, visit the Google Cloud sample browser.

Objectives

Costs

This tutorial uses the following billable components of Google Cloud:

  • Cloud Functions
  • Cloud Build
  • Pub/Sub
  • Cloud Storage
  • Artifact Registry
  • Eventarc
  • Cloud Logging

For details, see Cloud Functions pricing.

To generate a cost estimate based on your projected usage, use the pricing calculator. New Google Cloud users might be eligible for a free trial.


For step-by-step guidance on this task directly in Cloud Shell Editor, click Guide me:

Guide me


The following sections take you through the same steps as clicking Guide me.

Before you begin

  1. 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.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.

  4. Enable the Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Cloud Storage, Logging, and Pub/Sub APIs.

    Enable the APIs

  5. Install and initialize the Google Cloud CLI.
  6. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  7. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.

  8. Enable the Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Cloud Storage, Logging, and Pub/Sub APIs.

    Enable the APIs

  9. Install and initialize the Google Cloud CLI.
  10. If you already have the gcloud CLI installed, update it by running the following command:

    gcloud components update
  11. Prepare your development environment:

Prerequisites

  1. Create a regional bucket, where YOUR_BUCKET_NAME is a globally unique bucket name, and REGION is the region in which you plan to deploy your function:

    gsutil mb -l REGION gs://YOUR_BUCKET_NAME
    
  2. To use Cloud Storage functions, grant the pubsub.publisher role to the Cloud Storage service account:

    PROJECT_ID=$(gcloud config get-value project)
    PROJECT_NUMBER=$(gcloud projects list --filter="project_id:$PROJECT_ID" --format='value(project_number)')
    
    SERVICE_ACCOUNT=$(gsutil kms serviceaccount -p $PROJECT_NUMBER)
    
    gcloud projects add-iam-policy-binding $PROJECT_ID \
      --member serviceAccount:$SERVICE_ACCOUNT \
      --role roles/pubsub.publisher
    

Preparing the application

  1. 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.

    C#

    git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

    Ruby

    git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

    PHP

    git clone https://github.com/GoogleCloudPlatform/php-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

  2. Change to the directory that contains the Cloud Functions sample code:

    Node.js

    cd nodejs-docs-samples/functions/v2/helloGCS/

    Python

    cd python-docs-samples/functions/v2/storage/

    Go

    cd golang-samples/functions/functionsv2/hellostorage/

    Java

    cd java-docs-samples/functions/v2/hello-gcs/

    C#

    cd dotnet-docs-samples/functions/helloworld/HelloGcs/

    Ruby

    cd ruby-docs-samples/functions/helloworld/storage/

    PHP

    cd php-docs-samples/functions/helloworld_storage/

Deploying and triggering the function

Currently, Cloud Storage functions are based on Pub/Sub notifications from Cloud Storage and support similar event types:

The following sections describe how to deploy and trigger a function for each of these event types.

Object Finalize

Object finalize events trigger when a "write" of a Cloud Storage Object is successfully finalized. In particular, this means that creating a new object or overwriting an existing object triggers this event. Archive and metadata update operations are ignored by this trigger.

Object Finalize: deploying the function

Take a look at the sample function, which handles Cloud Storage events:

Node.js

const functions = require('@google-cloud/functions-framework');

// Register a CloudEvent callback with the Functions Framework that will
// be triggered by Cloud Storage.
functions.cloudEvent('helloGCS', cloudEvent => {
  console.log(`Event ID: ${cloudEvent.id}`);
  console.log(`Event Type: ${cloudEvent.type}`);

  const file = cloudEvent.data;
  console.log(`Bucket: ${file.bucket}`);
  console.log(`File: ${file.name}`);
  console.log(`Metageneration: ${file.metageneration}`);
  console.log(`Created: ${file.timeCreated}`);
  console.log(`Updated: ${file.updated}`);
});

Python

import functions_framework


# Triggered by a change in a storage bucket
@functions_framework.cloud_event
def hello_gcs(cloud_event):
    data = cloud_event.data

    event_id = cloud_event["id"]
    event_type = cloud_event["type"]

    bucket = data["bucket"]
    name = data["name"]
    metageneration = data["metageneration"]
    timeCreated = data["timeCreated"]
    updated = data["updated"]

    print(f"Event ID: {event_id}")
    print(f"Event type: {event_type}")
    print(f"Bucket: {bucket}")
    print(f"File: {name}")
    print(f"Metageneration: {metageneration}")
    print(f"Created: {timeCreated}")
    print(f"Updated: {updated}")

Go


// Package helloworld provides a set of Cloud Functions samples.
package helloworld

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
	"github.com/cloudevents/sdk-go/v2/event"
)

func init() {
	functions.CloudEvent("HelloStorage", helloStorage)
}

// StorageObjectData contains metadata of the Cloud Storage object.
type StorageObjectData struct {
	Bucket         string    `json:"bucket,omitempty"`
	Name           string    `json:"name,omitempty"`
	Metageneration int64     `json:"metageneration,string,omitempty"`
	TimeCreated    time.Time `json:"timeCreated,omitempty"`
	Updated        time.Time `json:"updated,omitempty"`
}

// helloStorage consumes a CloudEvent message and logs details about the changed object.
func helloStorage(ctx context.Context, e event.Event) error {
	log.Printf("Event ID: %s", e.ID())
	log.Printf("Event Type: %s", e.Type())

	var data StorageObjectData
	if err := e.DataAs(&data); err != nil {
		return fmt.Errorf("event.DataAs: %v", err)
	}

	log.Printf("Bucket: %s", data.Bucket)
	log.Printf("File: %s", data.Name)
	log.Printf("Metageneration: %d", data.Metageneration)
	log.Printf("Created: %s", data.TimeCreated)
	log.Printf("Updated: %s", data.Updated)
	return nil
}

Java

import com.google.cloud.functions.CloudEventsFunction;
import com.google.gson.Gson;
import functions.eventpojos.GcsEvent;
import io.cloudevents.CloudEvent;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

public class HelloGcs implements CloudEventsFunction {
  private static final Logger logger = Logger.getLogger(HelloGcs.class.getName());

  @Override
  public void accept(CloudEvent event) {
    logger.info("Event: " + event.getId());
    logger.info("Event Type: " + event.getType());

    if (event.getData() != null) {
      String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
      Gson gson = new Gson();
      GcsEvent gcsEvent = gson.fromJson(cloudEventData, GcsEvent.class);

      logger.info("Bucket: " + gcsEvent.getBucket());
      logger.info("File: " + gcsEvent.getName());
      logger.info("Metageneration: " + gcsEvent.getMetageneration());
      logger.info("Created: " + gcsEvent.getTimeCreated());
      logger.info("Updated: " + gcsEvent.getUpdated());
    }
  }
}

C#

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Cloud.Storage.V1;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;

namespace HelloGcs
{
     /// <summary>
     /// Example Cloud Storage-triggered function.
     /// This function can process any event from Cloud Storage.
     /// </summary>
    public class Function : ICloudEventFunction<StorageObjectData>
    {
        private readonly ILogger _logger;

        public Function(ILogger<Function> logger) =>
            _logger = logger;

        public Task HandleAsync(CloudEvent cloudEvent, StorageObjectData data, CancellationToken cancellationToken)
        {
            _logger.LogInformation("Event: {event}", cloudEvent.Id);
            _logger.LogInformation("Event Type: {type}", cloudEvent.Type);
            _logger.LogInformation("Bucket: {bucket}", data.Bucket);
            _logger.LogInformation("File: {file}", data.Name);
            _logger.LogInformation("Metageneration: {metageneration}", data.Metageneration);
            _logger.LogInformation("Created: {created:s}", data.TimeCreated?.ToDateTimeOffset());
            _logger.LogInformation("Updated: {updated:s}", data.Updated?.ToDateTimeOffset());
            return Task.CompletedTask;
        }
    }
}

Ruby

require "functions_framework"

FunctionsFramework.cloud_event "hello_gcs" do |event|
  # This function supports all Cloud Storage events.
  # The `event` parameter is a CloudEvents::Event::V1 object.
  # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
  payload = event.data

  logger.info "Event: #{event.id}"
  logger.info "Event Type: #{event.type}"
  logger.info "Bucket: #{payload['bucket']}"
  logger.info "File: #{payload['name']}"
  logger.info "Metageneration: #{payload['metageneration']}"
  logger.info "Created: #{payload['timeCreated']}"
  logger.info "Updated: #{payload['updated']}"
end

PHP


use CloudEvents\V1\CloudEventInterface;
use Google\CloudFunctions\FunctionsFramework;

// Register the function with Functions Framework.
// This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=cloudevent` environment
// variable when deploying. The `FUNCTION_TARGET` environment variable should
// match the first parameter.
FunctionsFramework::cloudEvent('helloGCS', 'helloGCS');

function helloGCS(CloudEventInterface $cloudevent)
{
    // This function supports all Cloud Storage event types.
    $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
    $data = $cloudevent->getData();
    fwrite($log, 'Event: ' . $cloudevent->getId() . PHP_EOL);
    fwrite($log, 'Event Type: ' . $cloudevent->getType() . PHP_EOL);
    fwrite($log, 'Bucket: ' . $data['bucket'] . PHP_EOL);
    fwrite($log, 'File: ' . $data['name'] . PHP_EOL);
    fwrite($log, 'Metageneration: ' . $data['metageneration'] . PHP_EOL);
    fwrite($log, 'Created: ' . $data['timeCreated'] . PHP_EOL);
    fwrite($log, 'Updated: ' . $data['updated'] . PHP_EOL);
}

To deploy the function, run the following command in the directory where the sample code is located:

Node.js

gcloud functions deploy nodejs-finalize-function \
--gen2 \
--runtime=nodejs16 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Node.js version:
  • nodejs16 (recommended)
  • nodejs14
  • nodejs12
  • nodejs10

Python

gcloud functions deploy python-finalize-function \
--gen2 \
--runtime=python310 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Python version:
  • python310 (recommended)
  • python39
  • python38
  • python37

Go

gcloud functions deploy go-finalize-function \
--gen2 \
--runtime=go116 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Go version:
  • go116 (recommended)
  • go113
  • go111

Java

gcloud functions deploy java-finalize-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Java version:
  • java17 (recommended)
  • java11

C#

gcloud functions deploy csharp-finalize-function \
--gen2 \
--runtime=dotnet3 \
--region=REGION \
--source=. \
--entry-point=HelloGcs.Function \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Ruby

gcloud functions deploy ruby-finalize-function \
--gen2 \
--runtime=ruby30 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Ruby version:
  • ruby30 (recommended)
  • ruby27
  • ruby26

PHP

gcloud functions deploy php-finalize-function \
--gen2 \
--runtime=php81 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred PHP version:
  • php81 (recommended)
  • php74

where YOUR_BUCKET_NAME is the name of the Cloud Storage bucket that triggers the function.

Object Finalize: triggering the function

Test the function by uploading a file to your bucket:

echo "Hello World" > test-finalize.txt
gsutil cp test-finalize.txt gs://YOUR_BUCKET_NAME/test-finalize.txt

You should see the received CloudEvent in the logs:

gcloud beta functions logs read YOUR_FUNCTION_NAME --gen2 --limit=100

Object Delete

Object delete events are most useful for non-versioning buckets. They are triggered when an old version of an object is deleted. In addition, they are triggered when an object is overwritten. Object delete triggers can also be used with versioning buckets, triggering when a version of an object is permanently deleted.

Object Delete: deploying the function

Using the same sample code as in the finalize example, deploy the function with object delete as the trigger event. Run the following command in the directory where the sample code is located:

Node.js

gcloud functions deploy nodejs-delete-function \
--gen2 \
--runtime=nodejs16 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Node.js version:
  • nodejs16 (recommended)
  • nodejs14
  • nodejs12
  • nodejs10

Python

gcloud functions deploy python-delete-function \
--gen2 \
--runtime=python310 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Python version:
  • python310 (recommended)
  • python39
  • python38
  • python37

Go

gcloud functions deploy go-delete-function \
--gen2 \
--runtime=go116 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Go version:
  • go116 (recommended)
  • go113
  • go111

Java

gcloud functions deploy java-delete-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Java version:
  • java17 (recommended)
  • java11

C#

gcloud functions deploy csharp-delete-function \
--gen2 \
--runtime=dotnet3 \
--region=REGION \
--source=. \
--entry-point=HelloGcs.Function \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Ruby

gcloud functions deploy ruby-delete-function \
--gen2 \
--runtime=ruby30 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Ruby version:
  • ruby30 (recommended)
  • ruby27
  • ruby26

PHP

gcloud functions deploy php-delete-function \
--gen2 \
--runtime=php81 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred PHP version:
  • php81 (recommended)
  • php74

where YOUR_BUCKET_NAME is the name of the Cloud Storage bucket that triggers the function.

Object Delete: triggering the function

To trigger the function:

  1. Create an empty test-delete.txt file in the directory where the sample code is located.

  2. Make sure that your bucket is non-versioning:

    gsutil versioning set off gs://YOUR_BUCKET_NAME
    
  3. Upload the file to Cloud Storage:

    gsutil cp test-delete.txt gs://YOUR_BUCKET_NAME
    

    where YOUR_BUCKET_NAME is the name of your Cloud Storage bucket where you will upload a test file. At this point the function should not execute yet.

  4. Delete the file to trigger the function:

    gsutil rm gs://YOUR_BUCKET_NAME/test-delete.txt
    
  5. You should see the received CloudEvent in the logs:

    gcloud beta functions logs read YOUR_FUNCTION_NAME --gen2 --limit=100

Note that the function may take some time to finish executing.

Object Archive

Object archive events can be used only with versioning buckets. They are triggered when an old version of an object is archived. In particular, this means that when an object is overwritten or deleted, an archive event is triggered.

Object Archive: deploying the function

Using the same sample code as in the finalize example, deploy the function with object archive as the trigger event. Run the following command in the directory where the sample code is located:

Node.js

gcloud functions deploy nodejs-archive-function \
--gen2 \
--runtime=nodejs16 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Node.js version:
  • nodejs16 (recommended)
  • nodejs14
  • nodejs12
  • nodejs10

Python

gcloud functions deploy python-archive-function \
--gen2 \
--runtime=python310 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Python version:
  • python310 (recommended)
  • python39
  • python38
  • python37

Go

gcloud functions deploy go-archive-function \
--gen2 \
--runtime=go116 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Go version:
  • go116 (recommended)
  • go113
  • go111

Java

gcloud functions deploy java-archive-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Java version:
  • java17 (recommended)
  • java11

C#

gcloud functions deploy csharp-archive-function \
--gen2 \
--runtime=dotnet3 \
--region=REGION \
--source=. \
--entry-point=HelloGcs.Function \
--trigger-event-filters="google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Ruby

gcloud functions deploy ruby-archive-function \
--gen2 \
--runtime=ruby30 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Ruby version:
  • ruby30 (recommended)
  • ruby27
  • ruby26

PHP

gcloud functions deploy php-archive-function \
--gen2 \
--runtime=php81 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred PHP version:
  • php81 (recommended)
  • php74

where YOUR_BUCKET_NAME is the name of the Cloud Storage bucket that triggers the function.

Object Archive: triggering the function

To trigger the function:

  1. Create an empty test-archive.txt file in the directory where the sample code is located.

  2. Make sure that your bucket has versioning enabled:

    gsutil versioning set on gs://YOUR_BUCKET_NAME
    
  3. Upload the file to Cloud Storage:

    gsutil cp test-archive.txt gs://YOUR_BUCKET_NAME
    

    where YOUR_BUCKET_NAME is the name of your Cloud Storage bucket where you will upload a test file. At this point the function should not execute yet.

  4. Archive the file to trigger the function:

    gsutil rm gs://YOUR_BUCKET_NAME/test-archive.txt
    
  5. You should see the received CloudEvent in the logs:

    gcloud beta functions logs read YOUR_FUNCTION_NAME --gen2 --limit=100

Object Metadata Update

Metadata update events are triggered when the metadata of existing object is updated.

Object Metadata Update: deploying the function

Using the same sample code as in the finalize example, deploy the function with metadata update as the trigger event. Run the following command in the directory where the sample code is located:

Node.js

gcloud functions deploy nodejs-metadata-function \
--gen2 \
--runtime=nodejs16 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Node.js version:
  • nodejs16 (recommended)
  • nodejs14
  • nodejs12
  • nodejs10

Python

gcloud functions deploy python-metadata-function \
--gen2 \
--runtime=python310 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Python version:
  • python310 (recommended)
  • python39
  • python38
  • python37

Go

gcloud functions deploy go-metadata-function \
--gen2 \
--runtime=go116 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Go version:
  • go116 (recommended)
  • go113
  • go111

Java

gcloud functions deploy java-metadata-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Java version:
  • java17 (recommended)
  • java11

C#

gcloud functions deploy csharp-metadata-function \
--gen2 \
--runtime=dotnet3 \
--region=REGION \
--source=. \
--entry-point=HelloGcs.Function \
--trigger-event-filters="google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Ruby

gcloud functions deploy ruby-metadata-function \
--gen2 \
--runtime=ruby30 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred Ruby version:
  • ruby30 (recommended)
  • ruby27
  • ruby26

PHP

gcloud functions deploy php-metadata-function \
--gen2 \
--runtime=php81 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"
You can use the following values for the --runtime flag to specify your preferred PHP version:
  • php81 (recommended)
  • php74

where YOUR_BUCKET_NAME is the name of the Cloud Storage bucket that triggers the function.

Object Metadata Update: triggering the function

To trigger the function:

  1. Create an empty test-metadata.txt file in the directory where the sample code is located.

  2. Make sure that your bucket is non-versioning:

    gsutil versioning set off gs://YOUR_BUCKET_NAME
    
  3. Upload the file to Cloud Storage:

    gsutil cp test-metadata.txt gs://YOUR_BUCKET_NAME
    

    where YOUR_BUCKET_NAME is the name of your Cloud Storage bucket where you will upload a test file. At this point the function should not execute yet.

  4. Update the metadata of the file:

    gsutil -m setmeta -h "Content-Type:text/plain" gs://YOUR_BUCKET_NAME/test-metadata.txt
    
  5. You should see the received CloudEvent in the logs:

    gcloud beta functions logs read YOUR_FUNCTION_NAME --gen2 --limit=100

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:

  1. In the console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

Deleting the Cloud Function

Deleting Cloud Functions does not remove any resources stored in Cloud Storage.

To delete the Cloud Function you created in this tutorial, run the following command:

gcloud functions delete YOUR_FUNCTION_NAME --gen2 --region REGION

You can also delete Cloud Functions from the Google Cloud console.

What's next