Cloud Storage 튜토리얼(1세대)


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

Cloud Storage 자체를 사용하기 위한 코드 샘플을 찾고 있다면 Google Cloud 샘플 브라우저를 방문하세요.

목표

비용

이 문서에서는 비용이 청구될 수 있는 다음과 같은 Google Cloud 구성요소를 사용합니다.

  • Cloud Functions
  • Cloud Storage

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용하세요. 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, Cloud Storage, and Eventarc 사용 설정

    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, Cloud Storage, and Eventarc 사용 설정

    API 사용 설정

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

    gcloud init
  12. gcloud CLI가 이미 설치되어 있으면 다음 명령어를 실행하여 업데이트합니다.

    gcloud components update
  13. 개발 환경을 준비합니다.

애플리케이션 준비

  1. 테스트 파일을 업로드할 Cloud Storage 버킷을 만듭니다. 여기서 YOUR_TRIGGER_BUCKET_NAME은 전역적으로 고유한 버킷 이름입니다.

    gsutil mb gs://YOUR_TRIGGER_BUCKET_NAME
    
  2. 샘플 앱 저장소를 로컬 머신에 클론합니다.

    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 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

  3. Cloud Functions 샘플 코드가 있는 디렉터리로 변경합니다.

    Node.js

    cd nodejs-docs-samples/functions/helloworld/

    Python

    cd python-docs-samples/functions/helloworld/

    Go

    cd golang-samples/functions/helloworld/

    Java

    cd java-docs-samples/functions/helloworld/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

/**
 * Generic background Cloud Function to be triggered by Cloud Storage.
 * This sample works for all Cloud Storage CRUD operations.
 *
 * @param {object} file The Cloud Storage file metadata.
 * @param {object} context The event metadata.
 */
exports.helloGCS = (file, context) => {
  console.log(`  Event: ${context.eventId}`);
  console.log(`  Event Type: ${context.eventType}`);
  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

def hello_gcs(event, context):
    """Background Cloud Function to be triggered by Cloud Storage.
       This generic function logs relevant data when a file is changed,
       and works for all Cloud Storage CRUD operations.
    Args:
        event (dict):  The dictionary with data specific to this type of event.
                       The `data` field contains a description of the event in
                       the Cloud Storage `object` format described here:
                       https://cloud.google.com/storage/docs/json_api/v1/objects#resource
        context (google.cloud.functions.Context): Metadata of triggering event.
    Returns:
        None; the output is written to Cloud Logging
    """

    print(f"Event ID: {context.event_id}")
    print(f"Event type: {context.event_type}")
    print("Bucket: {}".format(event["bucket"]))
    print("File: {}".format(event["name"]))
    print("Metageneration: {}".format(event["metageneration"]))
    print("Created: {}".format(event["timeCreated"]))
    print("Updated: {}".format(event["updated"]))

Go


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

import (
	"context"
	"fmt"
	"log"
	"time"

	"cloud.google.com/go/functions/metadata"
)

// GCSEvent is the payload of a GCS event.
type GCSEvent struct {
	Kind                    string                 `json:"kind"`
	ID                      string                 `json:"id"`
	SelfLink                string                 `json:"selfLink"`
	Name                    string                 `json:"name"`
	Bucket                  string                 `json:"bucket"`
	Generation              string                 `json:"generation"`
	Metageneration          string                 `json:"metageneration"`
	ContentType             string                 `json:"contentType"`
	TimeCreated             time.Time              `json:"timeCreated"`
	Updated                 time.Time              `json:"updated"`
	TemporaryHold           bool                   `json:"temporaryHold"`
	EventBasedHold          bool                   `json:"eventBasedHold"`
	RetentionExpirationTime time.Time              `json:"retentionExpirationTime"`
	StorageClass            string                 `json:"storageClass"`
	TimeStorageClassUpdated time.Time              `json:"timeStorageClassUpdated"`
	Size                    string                 `json:"size"`
	MD5Hash                 string                 `json:"md5Hash"`
	MediaLink               string                 `json:"mediaLink"`
	ContentEncoding         string                 `json:"contentEncoding"`
	ContentDisposition      string                 `json:"contentDisposition"`
	CacheControl            string                 `json:"cacheControl"`
	Metadata                map[string]interface{} `json:"metadata"`
	CRC32C                  string                 `json:"crc32c"`
	ComponentCount          int                    `json:"componentCount"`
	Etag                    string                 `json:"etag"`
	CustomerEncryption      struct {
		EncryptionAlgorithm string `json:"encryptionAlgorithm"`
		KeySha256           string `json:"keySha256"`
	}
	KMSKeyName    string `json:"kmsKeyName"`
	ResourceState string `json:"resourceState"`
}

// HelloGCS consumes a(ny) GCS event.
func HelloGCS(ctx context.Context, e GCSEvent) error {
	meta, err := metadata.FromContext(ctx)
	if err != nil {
		return fmt.Errorf("metadata.FromContext: %w", err)
	}
	log.Printf("Event ID: %v\n", meta.EventID)
	log.Printf("Event type: %v\n", meta.EventType)
	log.Printf("Bucket: %v\n", e.Bucket)
	log.Printf("File: %v\n", e.Name)
	log.Printf("Metageneration: %v\n", e.Metageneration)
	log.Printf("Created: %v\n", e.TimeCreated)
	log.Printf("Updated: %v\n", e.Updated)
	return nil
}

Java

import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import functions.eventpojos.GcsEvent;
import java.util.logging.Logger;

/**
 * Example Cloud Storage-triggered function.
 * This function can process any event from Cloud Storage.
 */
public class HelloGcs implements BackgroundFunction<GcsEvent> {
  private static final Logger logger = Logger.getLogger(HelloGcs.class.getName());

  @Override
  public void accept(GcsEvent event, Context context) {
    logger.info("Event: " + context.eventId());
    logger.info("Event Type: " + context.eventType());
    logger.info("Bucket: " + event.getBucket());
    logger.info("File: " + event.getName());
    logger.info("Metageneration: " + event.getMetageneration());
    logger.info("Created: " + event.getTimeCreated());
    logger.info("Updated: " + event.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 helloGCS \
--runtime nodejs20 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

Python

gcloud functions deploy hello_gcs \
--runtime python312 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

Go

gcloud functions deploy HelloGCS \
--runtime go121 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

Java

gcloud functions deploy java-gcs-function \
--entry-point functions.HelloGcs \
--runtime java17 \
--memory 512MB \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

C#

gcloud functions deploy csharp-gcs-function \
--entry-point HelloGcs.Function \
--runtime dotnet6 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

Ruby

gcloud functions deploy hello_gcs --runtime ruby32 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

PHP

 gcloud functions deploy helloGCS --runtime php82 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

여기서 YOUR_TRIGGER_BUCKET_NAME은 함수를 트리거하는 Cloud Storage 버킷 이름입니다.

객체 완료: 함수 트리거

함수 트리거는 다음 안내를 따르세요.

  1. 샘플 코드가 있는 디렉터리에서 빈 gcf-test.txt 파일을 만듭니다.

  2. 함수를 트리거하기 위해 해당 파일을 Cloud Storage에 업로드합니다.

    gsutil cp gcf-test.txt gs://YOUR_TRIGGER_BUCKET_NAME
    

    여기서 YOUR_TRIGGER_BUCKET_NAME은 테스트 파일을 업로드할 Cloud Storage 버킷 이름입니다.

  3. 로그를 확인하여 실행이 완료되었는지 확인합니다.

    gcloud functions logs read --limit 50
    

객체 삭제

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

객체 삭제: 함수 배포

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

Node.js

gcloud functions deploy helloGCS \
--runtime nodejs20 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

Python

gcloud functions deploy hello_gcs \
--runtime python312 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

Go

gcloud functions deploy HelloGCS \
--runtime go121 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

Java

gcloud functions deploy java-gcs-function \
--entry-point functions.HelloGcs \
--runtime java17 \
--memory 512MB \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

C#

gcloud functions deploy csharp-gcs-function \
--entry-point HelloGcs.Function \
--runtime dotnet6 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

Ruby

gcloud functions deploy hello_gcs --runtime ruby32 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

PHP

 gcloud functions deploy helloGCS --runtime php82 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

여기서 YOUR_TRIGGER_BUCKET_NAME은 함수를 트리거하는 Cloud Storage 버킷 이름입니다.

객체 삭제: 함수 트리거

함수 트리거는 다음 안내를 따르세요.

  1. 샘플 코드가 있는 디렉터리에서 빈 gcf-test.txt 파일을 만듭니다.

  2. 버전 관리 버킷이 아님을 확인합니다.

    gsutil versioning set off gs://YOUR_TRIGGER_BUCKET_NAME
    
  3. Cloud Storage에 파일을 업로드합니다.

    gsutil cp gcf-test.txt gs://YOUR_TRIGGER_BUCKET_NAME
    

    여기서 YOUR_TRIGGER_BUCKET_NAME은 테스트 파일을 업로드할 Cloud Storage 버킷 이름입니다. 이 시점에서 함수는 아직 실행되지 않아야 합니다.

  4. 파일을 삭제하여 함수를 트리거합니다.

    gsutil rm gs://YOUR_TRIGGER_BUCKET_NAME/gcf-test.txt
    
  5. 로그를 확인하여 실행이 완료되었는지 확인합니다.

    gcloud functions logs read --limit 50
    

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

객체 보관처리

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

객체 보관처리: 함수 배포

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

Node.js

gcloud functions deploy helloGCS \
--runtime nodejs20 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

Python

gcloud functions deploy hello_gcs \
--runtime python312 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

Go

gcloud functions deploy HelloGCS \
--runtime go121 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

Java

gcloud functions deploy java-gcs-function \
--entry-point functions.HelloGcs \
--runtime java17 \
--memory 512MB \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

C#

gcloud functions deploy csharp-gcs-function \
--entry-point HelloGcs.Function \
--runtime dotnet6 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

Ruby

gcloud functions deploy hello_gcs --runtime ruby32 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

PHP

 gcloud functions deploy helloGCS --runtime php82 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

여기서 YOUR_TRIGGER_BUCKET_NAME은 함수를 트리거하는 Cloud Storage 버킷 이름입니다.

객체 보관처리: 함수 트리거

함수 트리거는 다음 안내를 따르세요.

  1. 샘플 코드가 있는 디렉터리에서 빈 gcf-test.txt 파일을 만듭니다.

  2. 버킷에 버전 관리가 사용 설정되어 있는지 확인합니다.

    gsutil versioning set on gs://YOUR_TRIGGER_BUCKET_NAME
    
  3. Cloud Storage에 파일을 업로드합니다.

    gsutil cp gcf-test.txt gs://YOUR_TRIGGER_BUCKET_NAME
    

    여기서 YOUR_TRIGGER_BUCKET_NAME은 테스트 파일을 업로드할 Cloud Storage 버킷 이름입니다. 이 시점에서 함수는 아직 실행되지 않아야 합니다.

  4. 파일을 보관 처리하여 함수를 트리거합니다.

    gsutil rm gs://YOUR_TRIGGER_BUCKET_NAME/gcf-test.txt
    
  5. 로그를 통해 실행이 완료되었는지 확인합니다.

    gcloud functions logs read --limit 50
    

객체 메타데이터 업데이트

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

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

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

Node.js

gcloud functions deploy helloGCS \
--runtime nodejs20 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

Python

gcloud functions deploy hello_gcs \
--runtime python312 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

Go

gcloud functions deploy HelloGCS \
--runtime go121 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

Java

gcloud functions deploy java-gcs-function \
--entry-point functions.HelloGcs \
--runtime java17 \
--memory 512MB \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

C#

gcloud functions deploy csharp-gcs-function \
--entry-point HelloGcs.Function \
--runtime dotnet6 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

Ruby

gcloud functions deploy hello_gcs --runtime ruby32 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

PHP

 gcloud functions deploy helloGCS --runtime php82 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

여기서 YOUR_TRIGGER_BUCKET_NAME은 함수를 트리거하는 Cloud Storage 버킷 이름입니다.

객체 메타데이터 업데이트: 함수 트리거

함수 트리거는 다음 안내를 따르세요.

  1. 샘플 코드가 있는 디렉터리에서 빈 gcf-test.txt 파일을 만듭니다.

  2. 버전 관리 버킷이 아님을 확인합니다.

    gsutil versioning set off gs://YOUR_TRIGGER_BUCKET_NAME
    
  3. Cloud Storage에 파일을 업로드합니다.

    gsutil cp gcf-test.txt gs://YOUR_TRIGGER_BUCKET_NAME
    

    여기서 YOUR_TRIGGER_BUCKET_NAME은 테스트 파일을 업로드할 Cloud Storage 버킷 이름입니다. 이 시점에서 함수는 아직 실행되지 않아야 합니다.

  4. 파일의 메타데이터를 업데이트합니다.

    gsutil -m setmeta -h "Content-Type:text/plain" gs://YOUR_TRIGGER_BUCKET_NAME/gcf-test.txt
    
  5. 로그를 통해 실행이 완료되었는지 확인합니다.

    gcloud functions logs read --limit 50
    

삭제

이 튜토리얼에서 사용된 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 리소스가 포함된 프로젝트를 삭제하거나 프로젝트를 유지하고 개별 리소스를 삭제하세요.

프로젝트 삭제

비용이 청구되지 않도록 하는 가장 쉬운 방법은 튜토리얼에서 만든 프로젝트를 삭제하는 것입니다.

프로젝트를 삭제하려면 다음 안내를 따르세요.

  1. Google Cloud 콘솔에서 리소스 관리 페이지로 이동합니다.

    리소스 관리로 이동

  2. 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제를 클릭합니다.
  3. 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.

Cloud 함수 삭제

Cloud Functions를 삭제해도 Cloud Storage에 저장된 리소스는 삭제되지 않습니다.

이 튜토리얼에서 만든 Cloud Function을 삭제하려면 다음 명령어를 실행합니다.

Node.js

gcloud functions delete helloGCS 

Python

gcloud functions delete hello_gcs 

Go

gcloud functions delete HelloGCS 

Java

gcloud functions delete java-gcs-function 

C#

gcloud functions delete csharp-gcs-function 

Ruby

gcloud functions delete hello_gcs 

PHP

gcloud functions delete helloGCS 

Google Cloud 콘솔에서 Cloud Functions를 삭제할 수도 있습니다.

다음 단계