Google Cloud Storage Triggers

Cloud Functions can respond to Object Change Notifications emerging from Google Cloud Storage. These change notifications are triggered in response to object addition (create), update (modify), or deletion.

The following gcloud command deploys a function that will be triggered by Cloud Storage:

gcloud beta functions deploy helloWorld --stage-bucket cloud-functions --trigger-bucket my-bucket
Argument Description
--trigger-bucket <name> The name of the Cloud Storage bucket the function will watch for changes.

Cloud Storage Events

Cloud Functions triggered from Cloud Storage events will be sent an event containing an Objects resource representing the object in Cloud Storage that was created, updated or deleted. The format of the change notification is as per the published format for Objects.

Cloud Storage events will be triggered whenever an object is created, updated or deleted on a Cloud Storage bucket. To make it easy to distinguish in the Cloud Functions case, we've also included the resourceState property (usually sent as an HTTP header) in the body of the change notification in a property called resourceState, which will have the value exists for object additions and updates, or not_exists for object deletions.

You should pair the resourceState attribute with the metageneration attribute if you want to know if an object was just created or simply had its metadata updated. The metageneration attribute is incremented whenever there's a change to the object's metadata. For new objects, the metageneration value is 1.

For example:

Node.js

/**
 * Background Cloud Function to be triggered by Cloud Storage.
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} callback The callback function.
 */
exports.helloGCS = function (event, callback) {
  const file = event.data;

  if (file.resourceState === 'not_exists') {
    console.log(`File ${file.name} deleted.`);
  } else if (file.metageneration === '1') {
    // metageneration attribute is updated on metadata changes.
    // on create value is 1
    console.log(`File ${file.name} uploaded.`);
  } else {
    console.log(`File ${file.name} metadata updated.`);
  }

  callback();
};

Next steps

See the Cloud Storage Tutorial for an example of how to implement a background function that is triggered by Cloud Storage.

Send feedback about...

Cloud Functions Documentation