Tutorial Cloud Storage (generasi ke-1)


Tutorial sederhana ini menunjukkan penulisan, deployment, dan pemicuan fungsi Cloud Run 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 akan menggunakan komponen Google Cloudyang dapat ditagih berikut:

  • Cloud Run functions
  • Cloud Storage

Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda, gunakan kalkulator harga.

Pengguna Google Cloud baru mungkin memenuhi syarat untuk mendapatkan uji coba gratis.

Sebelum memulai

  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. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

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

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  7. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

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

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  13. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

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

    gcloud components update
  15. Menyiapkan lingkungan pengembangan:
  16. Menyiapkan aplikasi

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

      gcloud storage buckets create 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 contoh dalam file ZIP dan mengekstraknya.

      Python

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

      Atau, Anda dapat mendownload contoh dalam file ZIP dan mengekstraknya.

      Go

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

      Atau, Anda dapat mendownload contoh dalam file ZIP dan mengekstraknya.

      Java

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

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

      Ruby

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

      Atau, Anda dapat mendownload contoh dalam file ZIP dan mengekstraknya.

    3. Ubah ke direktori yang berisi kode contoh fungsi Cloud Run:

      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/

      Ruby

      cd ruby-docs-samples/functions/helloworld/storage/

    Men-deploy dan memicu fungsi

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

    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

    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.

    Ruby

    gcloud functions deploy hello_gcs --runtime ruby33 \
    -
    -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.

    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:

      gcloud storage 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 dipicu saat objek dihapus sementara. Hal ini terjadi saat objek ditimpa atau dihapus di bucket tanpa mengaktifkan Pembuatan Versi Objek. Menghapus objek dengan menentukan nomor generasinya juga akan menyebabkan objek dihapus sementara.

    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.

    Ruby

    gcloud functions deploy hello_gcs --runtime ruby33 \
    -
    -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.

    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:

      gcloud storage buckets update gs://YOUR_TRIGGER_BUCKET_NAME --no-versioning
    3. Upload file ke Cloud Storage:

      gcloud storage 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:

      gcloud storage 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 pengarsipan objek dipicu saat versi aktif sebuah objek menjadi versi lama. Hal ini terjadi saat objek ditimpa atau dihapus di bucket yang mengaktifkan Pembuatan Versi Objek.

    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.

    Ruby

    gcloud functions deploy hello_gcs --runtime ruby33 \
    -
    -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.

    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:

      gcloud storage buckets update gs://YOUR_TRIGGER_BUCKET_NAME --versioning
    3. Upload file ke Cloud Storage:

      gcloud storage 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:

      gcloud storage 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.

    Ruby

    gcloud functions deploy hello_gcs --runtime ruby33 \
    -
    -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.

    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:

      gcloud storage buckets update gs://YOUR_TRIGGER_BUCKET_NAME --no-versioning
    3. Upload file ke Cloud Storage:

      gcloud storage 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:

      gcloud storage objects update gs://YOUR_TRIGGER_BUCKET_NAME/gcf-test.txt --content-type=text/plain
    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. In the Google Cloud console, go to the Manage resources page.

      Go to Manage resources

    2. In the project list, select the project that you want to delete, and then click Delete.
    3. In the dialog, type the project ID, and then click Shut down to delete the project.

    Menghapus fungsi

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

    Untuk menghapus fungsi 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 

    Ruby

    gcloud functions delete hello_gcs 

    Anda juga dapat menghapus fungsi Cloud Run dari Google Cloud console.

    Langkah berikutnya