Cloud Storage の Pub/Sub 通知を構成する

概要

このページでは、オブジェクトの変更に関する通知を Pub/Sub トピックに送信するようにバケットを構成する方法について説明します。通知を受け取る Pub/Sub トピックへの登録の詳細については、サブスクリプション タイプの選択をご覧ください。

始める前に

この機能を使用する前に次の手順を完了します。

Pub/Sub API を有効にする

通知を受け取るプロジェクトの Pub/Sub API を有効にします。

API を有効にする

必要なロールを取得する

バケットの Pub/Sub 通知の構成と表示に必要な権限を取得するには、次のロールの付与を管理者に依頼します。これらの事前定義ロールには、Pub/Sub 通知の構成と表示に必要な権限が設定されています。

  • Pub/Sub 通知の構成対象バケットに対するストレージ管理者(roles/storage.admin)のロール

  • Pub/Sub 通知を受け取るプロジェクトに対する Pub/Sub 管理者(roles/pubsub.admin)のロール

これらの権限は、他の事前定義ロールカスタムロールを使用して取得することもできます。

バケットに対するロールを付与する方法については、バケットでの IAM ポリシーの設定と管理をご覧ください。プロジェクトに対するロールを付与する方法、およびトピックとサブスクリプションへのアクセス制御を設定する方法については、アクセス制御をご覧ください。

既存の Pub/Sub トピックがあることを確認する

まだ Pub/Sub トピックを作成していない場合は、通知の送信先とする Pub/Sub トピックを作成します。Google Cloud CLI または Terraform を使用してこのページの手順を実行する場合、この手順は不要です。

プロジェクトのサービス エージェントに必要なロールを付与する

Google Cloud CLI または Terraform を使用してこのページの手順を実行する場合、次の手順は不要です。

  1. Cloud Storage バケットを含むプロジェクトに関連付けられているサービス エージェントのメールアドレスを取得します。

  2. 関連する Pub/Sub トピックの Pub/Sub パブリッシャー(roles/pubsub.publisher)ロールをサービス エージェントに付与します。トピックのロールを付与する手順については、アクセスの制御をご覧ください。

通知構成を適用する

次の手順では、すべてのサポート対象イベントの通知を送信するバケットに通知構成を追加します。

コンソール

Google Cloud コンソールでは Pub/Sub 通知を管理できません。代わりに gcloud CLI または使用可能なクライアント ライブラリのいずれかを使用してください。

コマンドライン

gcloud storage buckets notifications create コマンドを使用します。

gcloud storage buckets notifications create gs://BUCKET_NAME --topic=TOPIC_NAME

ここで

  • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

  • TOPIC_NAME は、通知の送信先の Pub/Sub トピックです。プロジェクトに存在しないトピックを指定すると、トピックが作成されます。

イベントのサブセットに対して通知を送信するには、--event-types フラグを含めます。

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& topic_name) {
  StatusOr<gcs::NotificationMetadata> notification =
      client.CreateNotification(bucket_name, topic_name,
                                gcs::NotificationMetadata());
  if (!notification) throw std::move(notification).status();

  std::cout << "Successfully created notification " << notification->id()
            << " for bucket " << bucket_name << "\n";
  std::cout << "Full details for the notification:\n"
            << *notification << "\n";
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class CreatePubSubNotificationSample
{
    public Notification CreatePubSubNotification(
        string bucketName = "your-unique-bucket-name",
        string topic = "my-topic")
    {
        StorageClient storage = StorageClient.Create();
        Notification notification = new Notification
        {
            Topic = topic,
            PayloadFormat = "JSON_API_V1"
        };

        Notification createdNotification = storage.CreateNotification(bucketName, notification);
        Console.WriteLine("Notification subscription created with ID: " + createdNotification.Id + " for bucket name " + bucketName);
        return createdNotification;
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/storage"
)

// createBucketNotification creates a notification configuration for a bucket.
func createBucketNotification(w io.Writer, projectID, bucketName, topic string) error {
	// projectID := "my-project-id"
	// bucketName := "bucket-name"
	// topic := "topic-name"

	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	notification := storage.Notification{
		TopicID:        topic,
		TopicProjectID: projectID,
		PayloadFormat:  storage.JSONPayload,
	}

	createdNotification, err := client.Bucket(bucketName).AddNotification(ctx, &notification)
	if err != nil {
		return fmt.Errorf("Bucket.AddNotification: %w", err)
	}
	fmt.Fprintf(w, "Successfully created notification with ID %s for bucket %s.\n", createdNotification.ID, bucketName)
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

import com.google.cloud.storage.Notification;
import com.google.cloud.storage.NotificationInfo;
import com.google.cloud.storage.NotificationInfo.EventType;
import com.google.cloud.storage.NotificationInfo.PayloadFormat;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Map;

public class CreateBucketPubSubNotification {

  public static void createBucketPubSubNotification(
      String bucketName,
      String topicName,
      Map<String, String> customAttributes,
      EventType[] eventTypes,
      String objectNamePrefix,
      PayloadFormat payloadFormat) {
    // 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;

    Storage storage = StorageOptions.newBuilder().build().getService();
    NotificationInfo notificationInfo =
        NotificationInfo.newBuilder(topicName)
            .setCustomAttributes