Google Cloud Storage Triggers

Cloud Functions uses event-driven functions to handle events from your Cloud infrastructure. For example, Cloud Functions can respond to change notifications emerging from Google Cloud Storage. These notifications can be configured to trigger in response to various events inside a bucket—object creation, deletion, archiving and metadata updates.

Event Types

Cloud Storage events used by Cloud Functions are based on Cloud Pub/Sub Notifications for Google Cloud Storage and are provided in the Cloud Storage JSON API format.

Storage-triggered functions support four trigger types. These trigger type values are used upon function deployment to specify which Cloud Storage events will trigger your functions:

  • (default)




For example, the gcloud command shown below uses the trigger type to deploy a function that is invoked whenever the specified Cloud Storage bucket is written to.

Object Finalize

Trigger type value:

This event is sent when a new object is created (or an existing object is overwritten, and a new generation of that object is created) in the bucket.

For example, the following function logs relevant data when an event occurs:


 * Generic background Cloud Function to be triggered by Cloud Storage.
 * @param {object} file The Cloud Storage file metadata.
 * @param {object} context The event metadata.
exports.helloGCS = (file, context) => {
  console.log(`  Event: ${context.eventId}`);
  console.log(`  Event Type: ${context.eventType}`);
  console.log(`  Bucket: ${file.bucket}`);
  console.log(`  File: ${}`);
  console.log(`  Metageneration: ${file.metageneration}`);
  console.log(`  Created: ${file.timeCreated}`);
  console.log(`  Updated: ${file.updated}`);


def hello_gcs(event, context):
    """Background Cloud Function to be triggered by Cloud Storage.
       This generic function logs relevant data when a file is changed.

        event (dict):  The dictionary with data specific to this type of event.
                       The `data` field contains a description of the event in
                       the Cloud Storage `object` format described here:
        context ( Metadata of triggering event.
        None; the output is written to Stackdriver Logging

    print('Event ID: {}'.format(context.event_id))
    print('Event type: {}'.format(context.event_type))
    print('Bucket: {}'.format(event['bucket']))
    print('File: {}'.format(event['name']))
    print('Metageneration: {}'.format(event['metageneration']))
    print('Created: {}'.format(event['timeCreated']))
    print('Updated: {}'.format(event['updated']))



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

import (


// GCSEvent is the payload of a GCS event.
type GCSEvent struct {
	Kind                    string                 `json:"kind"`
	ID                      string                 `json:"id"`
	SelfLink                string                 `json:"selfLink"`
	Name                    string                 `json:"name"`
	Bucket                  string                 `json:"bucket"`
	Generation              string                 `json:"generation"`
	Metageneration          string                 `json:"metageneration"`
	ContentType             string                 `json:"contentType"`
	TimeCreated             time.Time              `json:"timeCreated"`
	Updated                 time.Time              `json:"updated"`
	TemporaryHold           bool                   `json:"temporaryHold"`
	EventBasedHold          bool                   `json:"eventBasedHold"`
	RetentionExpirationTime time.Time              `json:"retentionExpirationTime"`
	StorageClass            string                 `json:"storageClass"`
	TimeStorageClassUpdated time.Time              `json:"timeStorageClassUpdated"`
	Size                    string                 `json:"size"`
	MD5Hash                 string                 `json:"md5Hash"`
	MediaLink               string                 `json:"mediaLink"`
	ContentEncoding         string                 `json:"contentEncoding"`
	ContentDisposition      string                 `json:"contentDisposition"`
	CacheControl            string                 `json:"cacheControl"`
	Metadata                map[string]interface{} `json:"metadata"`
	CRC32C                  string                 `json:"crc32c"`
	ComponentCount          int                    `json:"componentCount"`
	Etag                    string                 `json:"etag"`
	CustomerEncryption      struct {
		EncryptionAlgorithm string `json:"encryptionAlgorithm"`
		KeySha256           string `json:"keySha256"`
	KMSKeyName    string `json:"kmsKeyName"`
	ResourceState string `json:"resourceState"`

// HelloGCS consumes a GCS event.
func HelloGCS(ctx context.Context, e GCSEvent) error {
	meta, err := metadata.FromContext(ctx)
	if err != nil {
		return fmt.Errorf("metadata.FromContext: %v", err)
	log.Printf("Event ID: %v\n", meta.EventID)
	log.Printf("Event type: %v\n", meta.EventType)
	log.Printf("Bucket: %v\n", e.Bucket)
	log.Printf("File: %v\n", e.Name)
	log.Printf("Metageneration: %v\n", e.Metageneration)
	log.Printf("Created: %v\n", e.TimeCreated)
	log.Printf("Updated: %v\n", e.Updated)
	return nil


import functions.eventpojos.GcsEvent;
import java.util.logging.Logger;

public class HelloGcs implements BackgroundFunction<GcsEvent> {
  private static final Logger logger = Logger.getLogger(HelloGcs.class.getName());

  public void accept(GcsEvent event, Context context) {"Event: " + context.eventId());"Event Type: " + context.eventType());"Bucket: " + event.getBucket());"File: " + event.getName());"Metageneration: " + event.getMetageneration());"Created: " + event.getTimeCreated());"Updated: " + event.getUpdated());


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
    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;


require "functions_framework"

FunctionsFramework.cloud_event "hello_gcs" do |event|
  # The event parameter is a CloudEvents::Event::V1 object.
  # See
  payload = "Event: #{}" "Event Type: #{event.type}" "Bucket: #{payload['bucket']}" "File: #{payload['name']}" "Metageneration: #{payload['metageneration']}" "Created: #{payload['timeCreated']}" "Updated: #{payload['updated']}"


use Google\CloudFunctions\CloudEvent;

function helloGCS(CloudEvent $cloudevent)
    $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);

Deploying the function

To deploy the function with an object finalize trigger, run the following command in the directory that contains the function code:


gcloud functions deploy helloGCS \
--runtime nodejs14 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
You can use the following values for the --runtime flag to specify your preferred Node.js version:
  • nodejs10
  • nodejs12
  • nodejs14


gcloud functions deploy hello_gcs \
--runtime python39 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
You can use the following values for the --runtime flag to specify your preferred Python version:
  • python37
  • python38
  • python39


gcloud functions deploy HelloGCS \
--runtime go113 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
You can use the following values for the --runtime flag to specify your preferred Go version:
  • go111 (Deprecated)
  • go113


gcloud functions deploy java-gcs-function \
--entry-point functions.HelloGcs \
--runtime java11 \
--memory 512MB \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \


gcloud functions deploy csharp-gcs-function \
--entry-point HelloGcs.Function \
--runtime dotnet3 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \


gcloud functions deploy hello_gcs --runtime ruby27 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
You can use the following values for the --runtime flag to specify your preferred Ruby version:
  • ruby26
  • ruby27


gcloud functions deploy helloGCS --runtime php74 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \

where YOUR_TRIGGER_BUCKET_NAME is the name of the Cloud Storage Bucket that the function will monitor.

Object Delete

Trigger type value:

This event is sent when an object is permanently deleted. Depending on the object versioning setting for a bucket this means:

  • For versioning buckets, this is only sent when a version is permanently deleted (but not when an object is archived).

  • For non-versioning buckets, this is sent when an object is deleted or overwritten.

Object Archive

Trigger type value:

This event is sent when a live version of an object is archived or deleted.

This event is only sent for versioning buckets.

Object Metadata Update

Trigger type value:

This event is sent when the metadata of an existing object changes.

Event structure

Storage event data is delivered in the Cloud Storage object format.

Event delivery mechanism

The events are delivered via Pub/Sub notifications from Cloud Storage. Setting up too many notifications registered against the same bucket may exhaust the notification limit for the bucket and make it impossible to create the function, as indicated by the error Cloud Storage bucket ...: Pub/Sub notification limit reached.

The bucket can have up to 10 notification configurations set to trigger for a specific event. See more quotas and limitations in the Cloud Storage Quotas & Limits page.

Legacy Cloud Storage triggers

The gcloud command below deploys a function that is triggered by legacy object change notifications on a specific bucket. Generally, Cloud Pub/Sub Notifications are easier to use, more flexible, and more powerful than object change notifications. However, these legacy notifications are supported for legacy functions already consuming these events.

gcloud functions deploy YOUR_FUNCTION_NAME \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event providers/ \
Argument Description
--trigger-resource NAME The name of the Cloud Storage bucket the function watches for changes.
--trigger-event NAME The name of the event type that the function wishes to receive. In this case, it is the legacy object.change event.
FLAGS... Additional flags you must specify during deployment, such as --runtime. For a full reference, see the gcloud functions deploy documentation.

Next steps

See the Cloud Storage Tutorial for an example of how to implement an event-driven function that is triggered by Cloud Storage.