Tutorial Cloud Storage (generasi ke-1)


Tutorial sederhana ini menunjukkan penulisan, deployment, dan pemicuan Cloud Function Berbasis Peristiwa dengan pemicu Cloud Storage untuk merespons peristiwa Cloud Storage.

Jika Anda mencari contoh kode untuk menggunakan Cloud Storage, buka browser contoh Google Cloud.

Tujuan

Biaya

Dalam dokumen ini, Anda menggunakan komponen Google Cloud yang dapat ditagih berikut:

  • Cloud Functions
  • Cloud Storage

Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda, gunakan kalkulator harga. Pengguna baru Google Cloud mungkin memenuhi syarat untuk mendapatkan uji coba gratis.


Untuk mengikuti panduan langkah demi langkah tugas ini langsung di Cloud Shell Editor, klik Pandu saya:

Pandu saya


Sebelum memulai

  1. Login ke akun Google Cloud Anda. Jika Anda baru menggunakan Google Cloud, buat akun untuk mengevaluasi performa produk kami dalam skenario dunia nyata. Pelanggan baru juga mendapatkan kredit gratis senilai $300 untuk menjalankan, menguji, dan men-deploy workload.
  2. Di konsol Google Cloud, pada halaman pemilih project, pilih atau buat project Google Cloud.

    Buka pemilih project

  3. Pastikan penagihan telah diaktifkan untuk project Google Cloud Anda.

  4. Enable the Cloud Functions, Cloud Build, Cloud Storage, and Eventarc APIs.

    Enable the APIs

  5. Menginstal Google Cloud CLI.
  6. Untuk initialize gcloud CLI, jalankan perintah berikut:

    gcloud init
  7. Di konsol Google Cloud, pada halaman pemilih project, pilih atau buat project Google Cloud.

    Buka pemilih project

  8. Pastikan penagihan telah diaktifkan untuk project Google Cloud Anda.

  9. Enable the Cloud Functions, Cloud Build, Cloud Storage, and Eventarc APIs.

    Enable the APIs

  10. Menginstal Google Cloud CLI.
  11. Untuk initialize gcloud CLI, jalankan perintah berikut:

    gcloud init
  12. Jika Anda sudah menginstal gcloud CLI, update dengan menjalankan perintah berikut:

    gcloud components update
  13. Menyiapkan lingkungan pengembangan:

Menyiapkan aplikasi

  1. Buat bucket Cloud Storage untuk mengupload file pengujian, dengan YOUR_TRIGGER_BUCKET_NAME adalah nama bucket yang unik secara global:

    gsutil mb gs://YOUR_TRIGGER_BUCKET_NAME
    
  2. Clone repositori aplikasi contoh ke komputer lokal Anda:

    Node.js

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

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

    Python

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

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

    Go

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

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

    Java

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

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

    C#

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

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

    Ruby

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

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

    PHP

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

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

  3. Ubah ke direktori yang memuat kode contoh 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/

Men-deploy dan memicu fungsi

Saat ini, fungsi Cloud Storage didasarkan pada notifikasi Pub/Sub dari Cloud Storage dan mendukung jenis peristiwa serupa:

Bagian berikut menjelaskan cara men-deploy dan memicu fungsi untuk setiap jenis peristiwa ini.

Finalisasi Objek

Peristiwa penyelesaian objek dipicu saat "penulisan" Objek Cloud Storage berhasil diselesaikan. Secara khusus, hal ini berarti bahwa membuat objek baru atau menimpa objek yang ada akan memicu peristiwa ini. Operasi update metadata dan arsip akan diabaikan oleh pemicu ini.

Finalisasi Objek: men-deploy fungsi

Lihat fungsi sampel, yang menangani peristiwa 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);
}

Untuk men-deploy fungsi, jalankan perintah berikut di direktori tempat kode contoh berada:

Node.js

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

Gunakan flag --runtime untuk menentukan ID runtime dari versi Node.js yang didukung untuk menjalankan fungsi Anda.

Python

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

Gunakan flag --runtime untuk menentukan ID runtime versi Python yang didukung untuk menjalankan fungsi Anda.

Go

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

Gunakan flag --runtime untuk menentukan ID runtime versi Go yang didukung untuk menjalankan fungsi Anda.

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

Gunakan flag --runtime untuk menentukan ID runtime versi Java yang didukung guna menjalankan fungsi Anda.

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

Gunakan flag --runtime untuk menentukan ID runtime versi .NET yang didukung guna menjalankan fungsi Anda.

Ruby

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

Gunakan flag --runtime untuk menentukan ID runtime versi Ruby yang didukung untuk menjalankan fungsi Anda.

PHP

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

Gunakan tanda --runtime untuk menentukan ID runtime versi PHP yang didukung untuk menjalankan fungsi Anda.

dengan YOUR_TRIGGER_BUCKET_NAME adalah nama bucket Cloud Storage yang memicu fungsi.

Finalisasi Objek: memicu fungsi

Untuk memicu fungsi:

  1. Buat file gcf-test.txt kosong di direktori tempat kode contoh berada.

  2. Upload file ke Cloud Storage untuk memicu fungsi:

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

    dengan YOUR_TRIGGER_BUCKET_NAME adalah nama bucket Cloud Storage tempat Anda akan mengupload file pengujian.

  3. Periksa log untuk memastikan eksekusi telah selesai:

    gcloud functions logs read --limit 50
    

Penghapusan Objek

Peristiwa penghapusan objek paling berguna untuk bucket non-pembuatan versi. Peristiwa ini dipicu saat objek versi lama dihapus. Selain itu, peristiwa ini dipicu saat objek ditimpa. Pemicu penghapusan objek juga dapat digunakan dengan bucket penetapan versi, yang memicu saat versi objek dihapus secara permanen.

Penghapusan Objek: men-deploy fungsi

Dengan menggunakan kode contoh yang sama seperti dalam contoh penyelesaian, deploy fungsi dengan penghapusan objek sebagai peristiwa pemicu. Jalankan perintah berikut di direktori tempat kode contoh berada:

Node.js

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

Gunakan flag --runtime untuk menentukan ID runtime dari versi Node.js yang didukung untuk menjalankan fungsi Anda.

Python

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

Gunakan flag --runtime untuk menentukan ID runtime versi Python yang didukung untuk menjalankan fungsi Anda.

Go

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

Gunakan flag --runtime untuk menentukan ID runtime versi Go yang didukung untuk menjalankan fungsi Anda.

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

Gunakan flag --runtime untuk menentukan ID runtime versi Java yang didukung guna menjalankan fungsi Anda.

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

Gunakan flag --runtime untuk menentukan ID runtime versi .NET yang didukung guna menjalankan fungsi Anda.

Ruby

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

Gunakan flag --runtime untuk menentukan ID runtime versi Ruby yang didukung untuk menjalankan fungsi Anda.

PHP

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

Gunakan tanda --runtime untuk menentukan ID runtime versi PHP yang didukung untuk menjalankan fungsi Anda.

dengan YOUR_TRIGGER_BUCKET_NAME adalah nama bucket Cloud Storage yang memicu fungsi.

Penghapusan Objek: memicu fungsi

Untuk memicu fungsi:

  1. Buat file gcf-test.txt kosong di direktori tempat kode contoh berada.

  2. Pastikan bucket Anda tidak membuat versi:

    gsutil versioning set off gs://YOUR_TRIGGER_BUCKET_NAME
    
  3. Upload file ke Cloud Storage:

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

    dengan YOUR_TRIGGER_BUCKET_NAME adalah nama bucket Cloud Storage tempat Anda akan mengupload file pengujian. Pada tahap ini, fungsi seharusnya belum dijalankan.

  4. Hapus file untuk memicu fungsi:

    gsutil rm gs://YOUR_TRIGGER_BUCKET_NAME/gcf-test.txt
    
  5. Periksa log untuk memastikan eksekusi telah selesai:

    gcloud functions logs read --limit 50
    

Perhatikan bahwa mungkin perlu waktu beberapa saat hingga fungsi selesai dijalankan.

Pengarsipan Objek

Peristiwa arsip objek hanya dapat digunakan dengan bucket pembuatan versi. Peristiwa dipicu saat versi lama objek diarsipkan. Secara khusus, hal ini berarti bahwa saat objek ditimpa atau dihapus, peristiwa arsip akan dipicu.

Arsip Objek: men-deploy fungsi

Dengan menggunakan kode contoh yang sama seperti dalam contoh penyelesaian, deploy fungsi dengan arsip objek sebagai peristiwa pemicu. Jalankan perintah berikut di direktori tempat kode contoh berada:

Node.js

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

Gunakan flag --runtime untuk menentukan ID runtime dari versi Node.js yang didukung untuk menjalankan fungsi Anda.

Python

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

Gunakan flag --runtime untuk menentukan ID runtime versi Python yang didukung untuk menjalankan fungsi Anda.

Go

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

Gunakan flag --runtime untuk menentukan ID runtime versi Go yang didukung untuk menjalankan fungsi Anda.

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

Gunakan flag --runtime untuk menentukan ID runtime versi Java yang didukung guna menjalankan fungsi Anda.

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

Gunakan flag --runtime untuk menentukan ID runtime versi .NET yang didukung guna menjalankan fungsi Anda.

Ruby

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

Gunakan flag --runtime untuk menentukan ID runtime versi Ruby yang didukung untuk menjalankan fungsi Anda.

PHP

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

Gunakan tanda --runtime untuk menentukan ID runtime versi PHP yang didukung untuk menjalankan fungsi Anda.

dengan YOUR_TRIGGER_BUCKET_NAME adalah nama bucket Cloud Storage yang memicu fungsi.

Arsip Objek: memicu fungsi

Untuk memicu fungsi:

  1. Buat file gcf-test.txt kosong di direktori tempat kode contoh berada.

  2. Pastikan bucket Anda mengaktifkan pembuatan versi:

    gsutil versioning set on gs://YOUR_TRIGGER_BUCKET_NAME
    
  3. Upload file ke Cloud Storage:

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

    dengan YOUR_TRIGGER_BUCKET_NAME adalah nama bucket Cloud Storage tempat Anda akan mengupload file pengujian. Pada tahap ini, fungsi seharusnya belum dijalankan.

  4. Arsipkan file untuk memicu fungsi:

    gsutil rm gs://YOUR_TRIGGER_BUCKET_NAME/gcf-test.txt
    
  5. Perhatikan log untuk memastikan eksekusi telah selesai:

    gcloud functions logs read --limit 50
    

Update Metadata Objek

Peristiwa pembaruan metadata dipicu saat metadata objek yang ada diperbarui.

Pembaruan Metadata Objek: men-deploy fungsi

Dengan menggunakan kode contoh yang sama seperti pada contoh penyelesaian, deploy fungsi dengan pembaruan metadata sebagai peristiwa pemicu. Jalankan perintah berikut di direktori tempat kode contoh berada:

Node.js

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

Gunakan flag --runtime untuk menentukan ID runtime dari versi Node.js yang didukung untuk menjalankan fungsi Anda.

Python

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

Gunakan flag --runtime untuk menentukan ID runtime versi Python yang didukung untuk menjalankan fungsi Anda.

Go

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

Gunakan flag --runtime untuk menentukan ID runtime versi Go yang didukung untuk menjalankan fungsi Anda.

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

Gunakan flag --runtime untuk menentukan ID runtime versi Java yang didukung guna menjalankan fungsi Anda.

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

Gunakan flag --runtime untuk menentukan ID runtime versi .NET yang didukung guna menjalankan fungsi Anda.

Ruby

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

Gunakan flag --runtime untuk menentukan ID runtime versi Ruby yang didukung untuk menjalankan fungsi Anda.

PHP

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

Gunakan tanda --runtime untuk menentukan ID runtime versi PHP yang didukung untuk menjalankan fungsi Anda.

dengan YOUR_TRIGGER_BUCKET_NAME adalah nama bucket Cloud Storage yang memicu fungsi.

Pembaruan Metadata Objek: memicu fungsi

Untuk memicu fungsi:

  1. Buat file gcf-test.txt kosong di direktori tempat kode contoh berada.

  2. Pastikan bucket Anda tidak membuat versi:

    gsutil versioning set off gs://YOUR_TRIGGER_BUCKET_NAME
    
  3. Upload file ke Cloud Storage:

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

    dengan YOUR_TRIGGER_BUCKET_NAME adalah nama bucket Cloud Storage tempat Anda akan mengupload file pengujian. Pada tahap ini, fungsi seharusnya belum dijalankan.

  4. Perbarui metadata file:

    gsutil -m setmeta -h "Content-Type:text/plain" gs://YOUR_TRIGGER_BUCKET_NAME/gcf-test.txt
    
  5. Perhatikan log untuk memastikan eksekusi telah selesai:

    gcloud functions logs read --limit 50
    

Pembersihan

Agar tidak dikenakan biaya pada akun Google Cloud Anda untuk resource yang digunakan dalam tutorial ini, hapus project yang berisi resource tersebut, atau simpan project dan hapus setiap resource-nya.

Menghapus project

Cara termudah untuk menghilangkan penagihan adalah dengan menghapus project yang Anda buat untuk tutorial.

Untuk menghapus project:

  1. Di konsol Google Cloud, buka halaman Manage resource.

    Buka Manage resource

  2. Pada daftar project, pilih project yang ingin Anda hapus, lalu klik Delete.
  3. Pada dialog, ketik project ID, lalu klik Shut down untuk menghapus project.

Menghapus Cloud Function

Menghapus Cloud Functions tidak akan menghapus resource apa pun yang tersimpan di Cloud Storage.

Untuk menghapus Cloud Function yang Anda buat dalam tutorial ini, jalankan perintah berikut:

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 

Anda juga dapat menghapus Cloud Functions dari Konsol Google Cloud.

Langkah selanjutnya