Cloud Storage 튜토리얼(2세대)


이 튜토리얼에서는 Cloud Storage 트리거를 사용하여 이벤트 기반 Cloud 함수를 작성, 배포, 트리거하여 Cloud Storage 이벤트에 응답하는 방법을 간략하게 설명합니다.

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. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. API Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Logging, and Pub/Sub 사용 설정

    API 사용 설정

  5. Google Cloud CLI를 설치합니다.
  6. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  7. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  8. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  9. API Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Logging, and Pub/Sub 사용 설정

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

함수를 배포하려면 샘플 코드가 있는 디렉터리에서 다음 명령어를 실행합니다.

// LINT.IfChange(nodejs_version) // LINT.ThenChange(:nodejs_version_console_text) // LINT.IfChange(nodejs_version_console_text) // LINT.ThenChange(:nodejs_version) // LINT.IfChange(nodejs_version) // LINT.ThenChange(:nodejs_version_console_text) // LINT.IfChange(nodejs_version_console_text) // LINT.ThenChange(:nodejs_version)

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Node.js 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Python 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Go 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Java 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 .NET 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Ruby 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 PHP 버전의 런타임 ID를 지정합니다.

다음을 바꿉니다.

  • 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

객체 삭제

객체 삭제 이벤트는 버전 관리 버킷이 아닌 경우에 가장 유용합니다. 해당 이벤트는 이전 버전의 객체가 삭제될 때 트리거됩니다. 또한 객체를 덮어쓸 때 트리거됩니다. 객체 삭제 트리거는 버전 관리 버킷과도 함께 사용 가능하며 객체의 버전이 영구적으로 삭제될 때 트리거됩니다.

객체 삭제: 함수 배포

완료 예와 동일한 샘플 코드를 사용하고 객체 삭제를 트리거 이벤트로 사용하여 함수를 배포합니다. 샘플 코드가 있는 디렉터리에서 다음 명령어를 실행합니다.

// LINT.IfChange(nodejs_version) // LINT.ThenChange(:nodejs_version_console_text) // LINT.IfChange(nodejs_version_console_text) // LINT.ThenChange(:nodejs_version) // LINT.IfChange(nodejs_version) // LINT.ThenChange(:nodejs_version_console_text) // LINT.IfChange(nodejs_version_console_text) // LINT.ThenChange(:nodejs_version)

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Node.js 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Python 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Go 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Java 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 .NET 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Ruby 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 PHP 버전의 런타임 ID를 지정합니다.

다음을 바꿉니다.

  • 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

함수의 실행을 완료하는 데 다소 시간이 걸릴 수 있습니다.

객체 보관처리

객체 보관처리 이벤트는 버전 관리 버킷에서만 사용할 수 있습니다. 해당 이벤트는 객체의 이전 버전이 보관처리될 때 발생합니다. 특히 보관처리 이벤트는 객체가 덮어쓰여지거나 삭제될 때 트리거됩니다.

객체 보관처리: 함수 배포

완료 예와 동일한 샘플 코드를 사용하고 객체 보관처리를 트리거 이벤트로 사용하여 함수를 배포합니다. 샘플 코드가 있는 디렉터리에서 다음 명령어를 실행합니다.

// LINT.IfChange(nodejs_version) // LINT.ThenChange(:nodejs_version_console_text) // LINT.IfChange(nodejs_version_console_text) // LINT.ThenChange(:nodejs_version) // LINT.IfChange(nodejs_version) // LINT.ThenChange(:nodejs_version_console_text) // LINT.IfChange(nodejs_version_console_text) // LINT.ThenChange(:nodejs_version)

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Node.js 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Python 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Go 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Java 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 .NET 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Ruby 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 PHP 버전의 런타임 ID를 지정합니다.

다음을 바꿉니다.

  • 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

객체 메타데이터 업데이트

메타데이터 업데이트 이벤트는 기존 객체의 메타데이터가 업데이트될 때 트리거됩니다.

객체 메타데이터 업데이트: 함수 배포

완료 예와 동일한 샘플 코드를 사용하고 메타데이터 업데이트를 트리거 이벤트로 사용하여 함수를 배포합니다. 샘플 코드가 있는 디렉터리에서 다음 명령어를 실행합니다.

// LINT.IfChange(nodejs_version) // LINT.ThenChange(:nodejs_version_console_text) // LINT.IfChange(nodejs_version_console_text) // LINT.ThenChange(:nodejs_version) // LINT.IfChange(nodejs_version) // LINT.ThenChange(:nodejs_version_console_text) // LINT.IfChange(nodejs_version_console_text) // LINT.ThenChange(:nodejs_version)

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Node.js 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Python 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Go 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Java 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 .NET 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Ruby 버전의 런타임 ID를 지정합니다.

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"

--runtime 플래그를 사용하여 함수를 실행할 지원되는 PHP 버전의 런타임 ID를 지정합니다.

다음을 바꿉니다.

  • 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를 삭제할 수도 있습니다.

다음 단계