This page describes how to configure your bucket to send notifications about
object changes to a Pub/Sub topic. For information on subscribing to a
Pub/Sub topic that receives notifications, see
Choose a subscription type.
Before you begin
Before using this feature, complete the following instructions.
Enable the Pub/Sub API
Enable the Pub/Sub API for the project that will
receive notifications.
If you haven't already, create a Pub/Sub topic to which
you want to send notifications. This step is not necessary if you plan on using
the Google Cloud CLI or Terraform to perform the instructions on this page.
Get required roles
IAM role requirements differ depending on whether you're
configuring the notification or delivering the event data:
If you use the Google Cloud CLI or Terraform to configure a notification,
your identity only needs permissions to update bucket metadata and view the
Pub/Sub topic. To get all the permissions required, follow the
instructions in
Get roles for viewing bucket metadata and the Pub/Sub topic.
If your Cloud Storage service agent is delivering notifications, it must
have the Pub/Sub Publisher role (roles/pubsub.publisher) on the
Pub/Sub topic. Once this role is configured for the service agent, the
service agent acts as a background "worker" to push events to your topic.
Get roles for viewing bucket metadata and the Pub/Sub topic
To get the permissions that you need to configure and view Pub/Sub
notifications for a bucket, ask your administrator to grant you the following
roles. These predefined roles contain the permissions required to configure and
view Pub/Sub notifications.
Storage Admin (roles/storage.admin) role on the bucket for which you want to
configure Pub/Sub notifications
Pub/Sub Admin (roles/pubsub.admin) role on the project in
which you want to receive Pub/Sub notifications
Grant the service agent the Pub/Sub Publisher
(roles/pubsub.publisher) role for the relevant Pub/Sub topic.
See Controlling access for instructions on granting roles for topics.
usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassCreatePubSubNotificationSample{publicNotificationCreatePubSubNotification(stringbucketName="your-unique-bucket-name",stringtopic="my-topic"){StorageClientstorage=StorageClient.Create();Notificationnotification=newNotification{Topic=topic,PayloadFormat="JSON_API_V1"};NotificationcreatedNotification=storage.CreateNotification(bucketName,notification);Console.WriteLine("Notification subscription created with ID: "+createdNotification.Id+" for bucket name "+bucketName);returncreatedNotification;}}
import("context""fmt""io""cloud.google.com/go/storage")// createBucketNotification creates a notification configuration for a bucket.funccreateBucketNotification(wio.Writer,projectID,bucketName,topicstring)error{// projectID := "my-project-id"// bucketName := "bucket-name"// topic := "topic-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()notification:=storage.Notification{TopicID:topic,TopicProjectID:projectID,PayloadFormat:storage.JSONPayload,}createdNotification,err:=client.Bucket(bucketName).AddNotification(ctx,¬ification)iferr!=nil{returnfmt.Errorf("Bucket.AddNotification: %w",err)}fmt.Fprintf(w,"Successfully created notification with ID %s for bucket %s.\n",createdNotification.ID,bucketName)returnnil}
importcom.google.cloud.storage.Notification;importcom.google.cloud.storage.NotificationInfo;importcom.google.cloud.storage.NotificationInfo.EventType;importcom.google.cloud.storage.NotificationInfo.PayloadFormat;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.util.Map;publicclassCreateBucketPubSubNotification{publicstaticvoidcreateBucketPubSubNotification(StringbucketName,StringtopicName,Map<String,String>customAttributes,EventType[]eventTypes,StringobjectNamePrefix,PayloadFormatpayloadFormat){// The ID to give your GCS bucket// String bucketName = "your-unique-bucket-name";// The name of the topic you would like to create a notification for// String topicName = "projects/{your-project}/topics/{your-topic}";// Any custom attributes// Map<String, String> customAttributes = Map.of("label", "value");// The object name prefix for which this notification configuration applies// String objectNamePrefix = "blob-";// Desired content of the Payload// PayloadFormat payloadFormat = PayloadFormat.JSON_API_V1.JSON_API_V1;Storagestorage=StorageOptions.newBuilder().build().getService();NotificationInfonotificationInfo=NotificationInfo.newBuilder(topicName).setCustomAttributes(customAttributes).setEventTypes(eventTypes).setObjectNamePrefix(objectNamePrefix).setPayloadFormat(payloadFormat).build();Notificationnotification=storage.createNotification(bucketName,notificationInfo);Stringtopic=notification.getTopic();System.out.println("Successfully created notification for topic "+topic);}}
/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The name of a topic// const topic = 'my-topic';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctioncreateNotification(){// Creates a notificationawaitstorage.bucket(bucketName).createNotification(topic);console.log('Notification subscription created.');}createNotification().catch(console.error);
fromgoogle.cloudimportstoragedefcreate_bucket_notifications(bucket_name,topic_name):"""Creates a notification configuration for a bucket."""# The ID of your GCS bucket# bucket_name = "your-bucket-name"# The name of a topic# topic_name = "your-topic-name"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)notification=bucket.notification(topic_name=topic_name)notification.create()print(f"Successfully created notification with ID {notification.notification_id} for bucket {bucket_name}")
require"google/cloud/storage"defcreate_bucket_notificationsbucket_name:,topic_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The ID of the pubsub topic# topic_name = "your-unique-topic-name"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namenotification=bucket.create_notificationtopic_nameputs"Successfully created notification with ID #{notification.id} for bucket #{bucket_name}"end
Terraform
You can use a Terraform resource to add a notification
configuration to a bucket.
// Create a Pub/Sub notification.
resource "google_storage_notification" "notification" {
provider = google-beta
bucket = google_storage_bucket.bucket.name
payload_format = "JSON_API_V1"
topic = google_pubsub_topic.topic.id
depends_on = [google_pubsub_topic_iam_binding.binding]
}
// Enable notifications by giving the correct IAM permission to the unique service account.
data "google_storage_project_service_account" "gcs_account" {
provider = google-beta
}
// Create a Pub/Sub topic.
resource "google_pubsub_topic_iam_binding" "binding" {
provider = google-beta
topic = google_pubsub_topic.topic.id
role = "roles/pubsub.publisher"
members = ["serviceAccount:${data.google_storage_project_service_account.gcs_account.email_address}"]
}
resource "random_id" "bucket_prefix" {
byte_length = 8
}
// Create a new storage bucket.
resource "google_storage_bucket" "bucket" {
name = "${random_id.bucket_prefix.hex}-example-bucket-name"
provider = google-beta
location = "US"
uniform_bucket_level_access = true
}
resource "google_pubsub_topic" "topic" {
name = "your_topic_name"
provider = google-beta
}
JSON_FILE_NAME is the path for the file
that you created in Step 2.
BUCKET_NAME is the name of the bucket you
want notifications to be generated for. For example, my-bucket.
XML API
You cannot manage Pub/Sub notifications with the XML API.
Apply a notification configuration across projects
Your bucket might be in a different project than the Pub/Sub topic you
want to send notifications to. For example, your bucket might be in Project A
while the Pub/Sub topic is in Project B. In this scenario, ensure the
following:
In Project B, grant the Pub/Sub Publisher role
(roles/pubsub.publisher) to Project A's Cloud Storage service agent on
the target topic. For more details, see
Grant required permission to service agent.
When creating the notification configuration in Project A, provide the full
path to the topic in Project B. For example:
projects/PROJECT_B_ID/topics/TOPIC_NAME
Get a notification configuration
To get a specific notification configuration that's associated with your bucket,
complete the following steps:
Console
You cannot manage Pub/Sub notifications with the
Google Cloud console. Use the Google Cloud CLI or one of the available
client libraries instead.
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst¬ification_id){StatusOr<gcs::NotificationMetadata>notification=client.GetNotification(bucket_name,notification_id);if(!notification)throwstd::move(notification).status();std::cout << "Notification " << notification->id() << " for bucket " << bucket_name << "\n";if(notification->object_name_prefix().empty()){std::cout << "This notification is sent for all objects in the bucket\n";}else{std::cout << "This notification is sent only for objects starting with" << " the prefix " << notification->object_name_prefix() << "\n";}std::cout << "Full details for the notification:\n" << *notification << "\n";}
importcom.google.cloud.storage.Notification;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassPrintPubSubNotification{publicstaticvoidprintPubSubNotification(StringbucketName,StringnotificationId){// The ID to give your GCS bucket// String bucketName = "your-unique-bucket-name";// The Pub/Sub topic you would like to find// String notificationId = "your-unique-notification-id"Storagestorage=StorageOptions.newBuilder().build().getService();Notificationnotification=storage.getNotification(bucketName,notificationId);System.out.println("Found notification "+notification.getTopic()+" for bucket "+bucketName);}}
/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The ID of the notification// const notificationId = '1';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiongetMetadata(){// Get the notification metadataconst[metadata]=awaitstorage.bucket(bucketName).notification(notificationId).getMetadata();console.log(`ID: ${metadata.id}`);console.log(`Topic: ${metadata.topic}`);console.log(`Event Types: ${metadata.event_types}`);console.log(`Custom Attributes: ${metadata.custom_attributes}`);console.log(`Payload Format: ${metadata.payload_format}`);console.log(`Object Name Prefix: ${metadata.object_name_prefix}`);console.log(`Etag: ${metadata.etag}`);console.log(`Self Link: ${metadata.selfLink}`);console.log(`Kind: ${metadata.kind}`);}getMetadata().catch(console.error);
fromgoogle.cloudimportstoragedefprint_pubsub_bucket_notification(bucket_name,notification_id):"""Gets a notification configuration for a bucket."""# The ID of your GCS bucket# bucket_name = "your-bucket-name"# The ID of the notification# notification_id = "your-notification-id"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)notification=bucket.get_notification(notification_id)print(f"Notification ID: {notification.notification_id}")print(f"Topic Name: {notification.topic_name}")print(f"Event Types: {notification.event_types}")print(f"Custom Attributes: {notification.custom_attributes}")print(f"Payload Format: {notification.payload_format}")print(f"Blob Name Prefix: {notification.blob_name_prefix}")print(f"Etag: {notification.etag}")print(f"Self Link: {notification.self_link}")
require"google/cloud/storage"defprint_pubsub_bucket_notificationbucket_name:,notification_id:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The ID of your notification configured for the bucket# notification_id = "your-notification-id"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namenotification=bucket.notificationnotification_idputs"Notification ID: #{notification.id}"puts"Topic Name: #{notification.topic}"puts"Event Types: #{notification.event_types}"puts"Kind of Notification: #{notification.kind}"puts"Custom Attributes: #{notification.custom_attrs}"puts"Payload Format: #{notification.payload}"puts"Blob Name Prefix: #{notification.prefix}"puts"Self Link: #{notification.api_url}"end
import("context""fmt""io""cloud.google.com/go/storage")// listBucketNotifications lists notification configurations for a bucket.funclistBucketNotifications(wio.Writer,bucketNamestring)error{// bucketName := "bucket-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()notifications,err:=client.Bucket(bucketName).Notifications(ctx)iferr!=nil{returnfmt.Errorf("Bucket.Notifications: %w",err)}fornID,n:=rangenotifications{fmt.Fprintf(w,"Notification topic %s with ID %s\n",n.TopicID,nID)}returnnil}
importcom.google.cloud.storage.Notification;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.util.List;publicclassListPubSubNotifications{publicstaticvoidlistPubSubNotifications(StringbucketName){// The ID to give your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().build().getService();List<Notification>notificationList=storage.listNotifications(bucketName);for(Notificationnotification:notificationList){System.out.println("Found notification "+notification.getTopic()+" for bucket "+bucketName);}}}
/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionlistNotifications(){// Lists notifications in the bucketconst[notifications]=awaitstorage.bucket(bucketName).getNotifications();console.log('Notifications:');notifications.forEach(notification=>{console.log(notification.id);});}listNotifications().catch(console.error);
fromgoogle.cloudimportstoragedeflist_bucket_notifications(bucket_name):"""Lists notification configurations for a bucket."""# The ID of your GCS bucket# bucket_name = "your-bucket-name"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)notifications=bucket.list_notifications()fornotificationinnotifications:print(f"Notification ID: {notification.notification_id}")
require"google/cloud/storage"deflist_bucket_notificationsbucket_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namebucket.notifications.eachdo|notification|puts"Notification ID: #{notification.id}"endend
usingSystem;usingGoogle.Cloud.Storage.V1;publicclassDeletePubSubNotificationSample{publicvoidDeletePubSubNotification(stringbucketName="your-unique-bucket-name",stringnotificationId="notificationId"){StorageClientstorage=StorageClient.Create();storage.DeleteNotification(bucketName,notificationId);Console.WriteLine("Successfully deleted notification with ID "+notificationId+" for bucket "+bucketName);}}
import("context""fmt""io""cloud.google.com/go/storage")// deleteBucketNotification deletes a notification configuration for a bucket.funcdeleteBucketNotification(wio.Writer,bucketName,notificationIDstring)error{// bucketName := "bucket-name"// notificationID := "notification-id"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()bucket:=client.Bucket(bucketName)iferr:=bucket.DeleteNotification(ctx,notificationID);err!=nil{returnfmt.Errorf("Bucket.DeleteNotification: %w",err)}fmt.Fprintf(w,"Successfully deleted notification with ID %s for bucket %s.\n",notificationID,bucketName)returnnil}
importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassDeleteBucketPubSubNotification{publicstaticvoiddeleteBucketPubSubNotification(StringbucketName,StringnotificationId){// The ID to give your GCS bucket// String bucketName = "your-unique-bucket-name";// The NotificationId for the notification you would like to delete// String notificationId = "your-unique-notification-id"Storagestorage=StorageOptions.newBuilder().build().getService();booleansuccess=storage.deleteNotification(bucketName,notificationId);if(success){System.out.println("Successfully deleted notification");}else{System.out.println("Failed to find notification");}}}
/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The ID of the notification// const notificationId = '1';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiondeleteNotification(){// Deletes the notification from the bucketawaitstorage.bucket(bucketName).notification(notificationId).delete();console.log(`Notification ${notificationId} deleted.`);}deleteNotification().catch(console.error);
fromgoogle.cloudimportstoragedefdelete_bucket_notification(bucket_name,notification_id):"""Deletes a notification configuration for a bucket."""# The ID of your GCS bucket# bucket_name = "your-bucket-name"# The ID of the notification# notification_id = "your-notification-id"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)notification=bucket.notification(notification_id=notification_id)notification.delete()print(f"Successfully deleted notification with ID {notification_id} for bucket {bucket_name}")
require"google/cloud/storage"defdelete_bucket_notificationbucket_name:,notification_id:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The ID of your notification configured for the bucket# notification_id = "your-notification-id"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namenotification=bucket.notificationnotification_idnotification.deleteputs"Successfully deleted notification with ID #{notification_id} for bucket #{bucket_name}"end
Terraform
To remove the notification configuration you created, run
terraform destroy from the folder containing your
Terraform file.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-06-09 UTC."],[],[]]