Cloud Storage のチュートリアル(第 2 世代)


このシンプルなチュートリアルでは、Cloud Storage イベントに応答する Cloud Storage トリガーを使用した Cloud Functions のイベント ドリブン関数を、作成、デプロイ、トリガーする方法について説明します。

Cloud Storage 自体を使用したコードサンプルについては、Google Cloud のサンプル ブラウザをご覧ください。

目標

費用

このドキュメントでは、Google Cloud の次の課金対象のコンポーネントを使用します。

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

詳細については、Cloud Functions の料金をご覧ください。

料金計算ツールを使うと、予想使用量に基づいて費用の見積もりを生成できます。 新しい Google Cloud ユーザーは無料トライアルをご利用いただける場合があります。


このタスクを Cloud Shell エディタで直接行う際のガイダンスについては、「ガイドを表示」をクリックしてください。

ガイドを表示


始める前に

  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. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Logging, and Pub/Sub API を有効にします。

    API を有効にする

  5. Google Cloud CLI をインストールします。
  6. gcloud CLI を初期化するには:

    gcloud init
  7. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  8. Google Cloud プロジェクトで課金が有効になっていることを確認します

  9. Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Logging, and Pub/Sub API を有効にします。

    API を有効にする

  10. Google Cloud CLI をインストールします。
  11. gcloud CLI を初期化するには:

    gcloud init
  12. gcloud CLI がすでにインストールされている場合は、次のコマンドを実行して更新します。

    gcloud components update
  13. 開発環境を準備します。

前提条件

  1. リージョン バケットを作成します。ここで、YOUR_BUCKET_NAME はグローバルに一意のバケット名で、REGION は関数をデプロイしたリージョンです。

    gsutil mb -l REGION gs://YOUR_BUCKET_NAME
    
  2. Cloud Storage の関数を使用するには、Cloud Storage サービス アカウントに pubsub.publisher ロールを付与します。

    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
    

アプリケーションを準備する

  1. ローカルマシンにサンプルアプリのリポジトリのクローンを作成します。

    Node.js

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

    また、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

    Python

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

    また、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

    Go

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    また、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

    Java

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

    また、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

    C#

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

    また、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

    Ruby

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

    また、zip 形式のサンプルをダウンロードし、ファイルを抽出してもかまいません。

    PHP

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

    または、zip 形式のサンプルをダウンロードし、ファイルを抽出してもかまいません。

  2. Cloud Functions のサンプルコードが含まれているディレクトリに移動します。

    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/

関数をデプロイしてトリガーする

Cloud Storage の関数は Cloud Storage からの Pub/Sub 通知に基づいており、以下に挙げる類似のイベントタイプに対応しています。

以降のセクションでは、上記の各イベントタイプについて、関数をデプロイしてトリガーする方法を説明します。

オブジェクトのファイナライズ

オブジェクト ファイナライズ イベントは、Cloud Storage オブジェクトの「書き込み」が正常にファイナライズされた時点でトリガーされます。つまり、新しいオブジェクトの作成または既存のオブジェクトの上書きによって、このイベントがトリガーされます。このトリガーにより、アーカイブとメタデータの更新オペレーションは無視されます。

オブジェクトのファイナライズ: 関数をデプロイする

Cloud Storage イベントを処理するサンプル関数を見てみましょう。

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

from cloudevents.http import CloudEvent

import functions_framework

# Triggered by a change in a storage bucket
@functions_framework.cloud_event
def hello_gcs(cloud_event: CloudEvent) -> tuple:
    """This function is triggered by a change in a storage bucket.

    Args:
        cloud_event: The CloudEvent that triggered this function.
    Returns:
        The event ID, event type, bucket, name, metageneration, and timeCreated.
    """
    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}")

    return event_id, event_type, bucket, name, metageneration, timeCreated, updated

Go


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

import (
	"context"
	"fmt"
	"log"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
	"github.com/cloudevents/sdk-go/v2/event"
	"github.com/googleapis/google-cloudevents-go/cloud/storagedata"
	"google.golang.org/protobuf/encoding/protojson"
)

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

// 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 storagedata.StorageObjectData
	if err := protojson.Unmarshal(e.Data(), &data); err != nil {
		return fmt.Errorf("protojson.Unmarshal: %w", err)
	}

	log.Printf("Bucket: %s", data.GetBucket())
	log.Printf("File: %s", data.GetName())
	log.Printf("Metageneration: %d", data.GetMetageneration())
	log.Printf("Created: %s", data.GetTimeCreated().AsTime())
	log.Printf("Updated: %s", data.GetUpdated().AsTime())
	return nil
}

Java

import com.google.cloud.functions.CloudEventsFunction;
import com.google.events.cloud.storage.v1.StorageObjectData;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
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) throws InvalidProtocolBufferException {
    logger.info("Event: " + event.getId());
    logger.info("Event Type: " + event.getType());

    if (event.getData() == null) {
      logger.warning("No data found in cloud event payload!");
      return;
    }

    String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
    StorageObjectData.Builder builder = StorageObjectData.newBuilder();
    JsonFormat.parser().merge(cloudEventData, builder);
    StorageObjectData data = builder.build();

    logger.info("Bucket: " + data.getBucket());
    logger.info("File: " + data.getName());
    logger.info("Metageneration: " + data.getMetageneration());
    logger.info("Created: " + data.getTimeCreated());
    logger.info("Updated: " + data.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);
}

関数をデプロイするには、サンプルコードがあるディレクトリで次のコマンドを実行します。

Node.js

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

サポートされている Node.js バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Python

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

サポートされている Python バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Go

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

サポートされている Go バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

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"

サポートされている Java バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

C#

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

サポートされている .NET バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Ruby

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

サポートされている Ruby バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

PHP

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

サポートされている PHP バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

次のように置き換えます。

  • REGION: 関数をデプロイする Google Cloud リージョンの名前(例: us-west1)。
  • YOUR_BUCKET_NAME: 関数をトリガーする Cloud Storage バケットの名前。第 2 世代の関数をデプロイする場合は、先頭に gs:// を付けずにバケット名のみを指定します(例: --trigger-event-filters="bucket=my-bucket")。

オブジェクトのファイナライズ: 関数をトリガーする

バケットにファイルをアップロードして関数をテストします。

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

受信した CloudEvent がログに表示されます。

gcloud functions logs read YOUR_FUNCTION_NAME --region REGION --gen2 --limit=10

オブジェクトの削除

オブジェクト削除イベントは、バージョニング非対応バケットには特に便利です。このイベントがトリガーされるのは、オブジェクトの古いバージョンが削除された時点です。さらに、オブジェクトが上書きされた場合にもトリガーされます。また、オブジェクト削除トリガーをバージョニング対応バケットで使用することもできます。この場合、オブジェクトのバージョンが完全に削除された時点でトリガーされます。

オブジェクトの削除: 関数をデプロイする

ファイナライズの例と同じサンプルコードを使用して、トリガー イベントとしてオブジェクトの削除を行う関数をデプロイします。サンプルコードがあるディレクトリで次のコマンドを実行します。

Node.js

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

サポートされている Node.js バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Python

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

サポートされている Python バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Go

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

サポートされている Go バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

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"

サポートされている Java バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

C#

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

サポートされている .NET バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Ruby

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

サポートされている Ruby バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

PHP

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

サポートされている PHP バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

次のように置き換えます。

  • REGION: 関数をデプロイする Google Cloud リージョンの名前(例: us-west1)。
  • YOUR_BUCKET_NAME: 関数をトリガーする Cloud Storage バケットの名前。第 2 世代の関数をデプロイする場合は、先頭に gs:// を付けずにバケット名のみを指定します(例: --trigger-event-filters="bucket=my-bucket")。

オブジェクトの削除: 関数をトリガーする

関数をトリガーするには:

  1. サンプルコードがあるディレクトリに空の test-delete.txt ファイルを作成します。

  2. バケットがバージョニング対応でないことを確認します。

    gsutil versioning set off gs://YOUR_BUCKET_NAME
    
  3. Cloud Storage にファイルをアップロードします。

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

    YOUR_BUCKET_NAME は、テストファイルをアップロードする Cloud Storage バケットの名前です。この時点ではまだ関数は実行されません。

  4. ファイルを削除して関数をトリガーします。

    gsutil rm gs://YOUR_BUCKET_NAME/test-delete.txt
    
  5. 受信した CloudEvent がログに表示されます。

    gcloud functions logs read YOUR_FUNCTION_NAME --region REGION --gen2 --limit=10

関数の実行が完了するまでに時間がかかる場合があることに注意してください。

オブジェクトのアーカイブ

オブジェクト アーカイブ イベントは、バージョニング対応バケットでのみ使用できます。このイベントがトリガーされるのは、オブジェクトの古いバージョンがアーカイブされた時点です。つまり、オブジェクトが上書きまたは削除されると、アーカイブ イベントがトリガーされます。

オブジェクトのアーカイブ: 関数をデプロイする

ファイナライズの例と同じサンプルコードを使用して、トリガー イベントとしてオブジェクトのアーカイブを行う関数をデプロイします。サンプルコードがあるディレクトリで次のコマンドを実行します。

Node.js

gcloud functions deploy nodejs-archive-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

サポートされている Node.js バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Python

gcloud functions deploy python-archive-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

サポートされている Python バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Go

gcloud functions deploy go-archive-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

サポートされている Go バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Java

gcloud functions deploy java-archive-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

サポートされている Java バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

C#

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

サポートされている .NET バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Ruby

gcloud functions deploy ruby-archive-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

サポートされている Ruby バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

PHP

gcloud functions deploy php-archive-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

サポートされている PHP バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

次のように置き換えます。

  • REGION: 関数をデプロイする Google Cloud リージョンの名前(例: us-west1)。
  • YOUR_BUCKET_NAME: 関数をトリガーする Cloud Storage バケットの名前。第 2 世代の関数をデプロイする場合は、先頭に gs:// を付けずにバケット名のみを指定します(例: --trigger-event-filters="bucket=my-bucket")。

オブジェクトのアーカイブ: 関数をトリガーする

関数をトリガーするには:

  1. サンプルコードがあるディレクトリに空の test-archive.txt ファイルを作成します。

  2. バケットのバージョニングが有効になっていることを確認します。

    gsutil versioning set on gs://YOUR_BUCKET_NAME
    
  3. Cloud Storage にファイルをアップロードします。

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

    YOUR_BUCKET_NAME は、テストファイルをアップロードする Cloud Storage バケットの名前です。この時点ではまだ関数は実行されません。

  4. ファイルをアーカイブして関数をトリガーします。

    gsutil rm gs://YOUR_BUCKET_NAME/test-archive.txt
    
  5. 受信した CloudEvent がログに表示されます。

    gcloud functions logs read YOUR_FUNCTION_NAME --region REGION --gen2 --limit=10

オブジェクト メタデータの更新

メタデータ更新イベントは、既存のオブジェクトのメタデータが更新された時点でトリガーされます。

オブジェクト メタデータの更新: 関数をデプロイする

ファイナライズの例と同じサンプルコードを使用して、トリガー イベントとしてメタデータの更新を行う関数をデプロイします。サンプルコードがあるディレクトリで次のコマンドを実行します。

Node.js

gcloud functions deploy nodejs-metadata-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

サポートされている Node.js バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Python

gcloud functions deploy python-metadata-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

サポートされている Python バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Go

gcloud functions deploy go-metadata-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

サポートされている Go バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Java

gcloud functions deploy java-metadata-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

サポートされている Java バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

C#

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

サポートされている .NET バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

Ruby

gcloud functions deploy ruby-metadata-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

サポートされている Ruby バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

PHP

gcloud functions deploy php-metadata-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

サポートされている PHP バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

次のように置き換えます。

  • REGION: 関数をデプロイする Google Cloud リージョンの名前(例: us-west1)。
  • YOUR_BUCKET_NAME: 関数をトリガーする Cloud Storage バケットの名前。第 2 世代の関数をデプロイする場合は、先頭に gs:// を付けずにバケット名のみを指定します(例: --trigger-event-filters="bucket=my-bucket")。

オブジェクト メタデータの更新: 関数をトリガーする

関数をトリガーするには:

  1. サンプルコードがあるディレクトリに空の test-metadata.txt ファイルを作成します。

  2. バケットがバージョニング対応でないことを確認します。

    gsutil versioning set off gs://YOUR_BUCKET_NAME
    
  3. Cloud Storage にファイルをアップロードします。

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

    YOUR_BUCKET_NAME は、テストファイルをアップロードする Cloud Storage バケットの名前です。この時点ではまだ関数は実行されません。

  4. ファイルのメタデータを更新します。

    gsutil -m setmeta -h "Content-Type:text/plain" gs://YOUR_BUCKET_NAME/test-metadata.txt
    
  5. 受信した CloudEvent がログに表示されます。

    gcloud functions logs read YOUR_FUNCTION_NAME --region REGION --gen2 --limit=10

クリーンアップ

このチュートリアルで使用したリソースについて、Google Cloud アカウントに課金されないようにするには、リソースを含むプロジェクトを削除するか、プロジェクトを維持して個々のリソースを削除します。

プロジェクトの削除

課金をなくす最も簡単な方法は、チュートリアル用に作成したプロジェクトを削除することです。

プロジェクトを削除するには:

  1. Google Cloud コンソールで、[リソースの管理] ページに移動します。

    [リソースの管理] に移動

  2. プロジェクト リストで、削除するプロジェクトを選択し、[削除] をクリックします。
  3. ダイアログでプロジェクト ID を入力し、[シャットダウン] をクリックしてプロジェクトを削除します。

Cloud Functions の関数を削除する

Cloud Functions の関数を削除しても、Cloud Storage に保存されたリソースが削除されることはありません。

このチュートリアルで作成した Cloud Functions の関数を削除するには、次のコマンドを実行します。

gcloud functions delete YOUR_FUNCTION_NAME --gen2 --region REGION

Google Cloud コンソールから Cloud Functions の関数を削除することもできます。

次のステップ