Tutorial su Cloud Storage (1ª generazione.)


Questo semplice tutorial illustra la scrittura, il deployment e l'attivazione di una funzione Cloud Functions Functions basata su eventi con un trigger di Cloud Storage per rispondere agli eventi di Cloud Storage.

Se stai cercando esempi di codice per utilizzare Cloud Storage visita il browser di esempio Google Cloud.

Obiettivi

Costi

In questo documento vengono utilizzati i seguenti componenti fatturabili di Google Cloud:

  • Cloud Functions
  • Cloud Storage

Per generare una stima dei costi basata sull'utilizzo previsto, utilizza il Calcolatore prezzi. I nuovi utenti di Google Cloud potrebbero essere idonei per una prova gratuita.


Per seguire una guida passo passo per questa attività direttamente nel Editor di Cloud Shell, fai clic su Procedura guidata:

Procedura guidata


Prima di iniziare

  1. Accedi al tuo account Google Cloud. Se non conosci Google Cloud, crea un account per valutare le prestazioni dei nostri prodotti in scenari reali. I nuovi clienti ricevono anche 300 $di crediti gratuiti per l'esecuzione, il test e il deployment dei carichi di lavoro.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Assicurati che la fatturazione sia attivata per il tuo progetto Google Cloud.

  4. Abilita le API Cloud Functions, Cloud Build, Cloud Storage, and Eventarc.

    Abilita le API

  5. Installa Google Cloud CLI.
  6. Per initialize gcloud CLI, esegui questo comando:

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

    Go to project selector

  8. Assicurati che la fatturazione sia attivata per il tuo progetto Google Cloud.

  9. Abilita le API Cloud Functions, Cloud Build, Cloud Storage, and Eventarc.

    Abilita le API

  10. Installa Google Cloud CLI.
  11. Per initialize gcloud CLI, esegui questo comando:

    gcloud init
  12. Se hai già installato gcloud CLI, aggiornalo eseguendo il seguente comando:

    gcloud components update
  13. Prepara l'ambiente di sviluppo:

Preparazione dell'applicazione

  1. Crea un bucket Cloud Storage per caricare un file di test, in cui YOUR_TRIGGER_BUCKET_NAME è un nome di bucket univoco a livello globale:

    gcloud storage buckets create gs://YOUR_TRIGGER_BUCKET_NAME
    
  2. Clona il repository dell'app di esempio nella tua macchina locale:

    Node.js

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

    In alternativa, puoi scarica l'esempio . come file ZIP ed estrarlo.

    Python

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

    In alternativa, puoi scarica l'esempio . come file ZIP ed estrarlo.

    Vai

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

    In alternativa, puoi scarica l'esempio . come file ZIP ed estrarlo.

    Java

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

    In alternativa, puoi scarica l'esempio . come file ZIP ed estrarlo.

    C#

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

    In alternativa, puoi scarica l'esempio . come file ZIP ed estrarlo.

    Ruby

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

    In alternativa, puoi scarica l'esempio . come file ZIP ed estrarlo.

    PHP

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

    In alternativa, puoi scarica l'esempio . come file ZIP ed estrarlo.

  3. Passa alla directory che contiene l'esempio di Cloud Functions codice:

    Node.js

    cd nodejs-docs-samples/functions/helloworld/

    Python

    cd python-docs-samples/functions/helloworld/

    Vai

    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/

Deployment e attivazione della funzione

Attualmente, le funzioni di Cloud Storage si basano su Notifiche Pub/Sub da Cloud Storage e supportano tipi di eventi simili:

Le sezioni seguenti descrivono come eseguire il deployment e attivare una funzione per ciascuno di questi tipi di eventi.

Finalizzazione oggetto

Gli eventi di finalizzazione degli oggetti vengono attivati quando viene eseguito un di Oggetto Cloud Storage è finalizzato correttamente. Nello specifico, ciò significa che la creazione di un nuovo oggetto la sovrascrittura di un oggetto esistente attiva questo evento. Archivio e metadati le operazioni di aggiornamento vengono ignorate da questo attivatore.

Finalizzazione oggetto: deployment della funzione

Dai un'occhiata alla funzione di esempio che gestisce gli eventi di 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"]))

Vai


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

Per eseguire il deployment della funzione, esegui questo comando nella directory in cui in cui si trova il codice campione:

Node.js

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

Utilizza la --runtime per specificare l'ID runtime di un versione Node.js supportata per l'esecuzione la tua funzione.

Python

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

Utilizza la --runtime per specificare l'ID runtime di un versione Python supportata per l'esecuzione la tua funzione.

Vai

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

Utilizza la --runtime per specificare l'ID runtime di un versione Go supportata per l'esecuzione la tua funzione.

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

Utilizza la --runtime per specificare l'ID runtime di un versione Java supportata per l'esecuzione la tua funzione.

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

Utilizza la --runtime per specificare l'ID runtime di un versione .NET supportata per l'esecuzione la tua funzione.

Ruby

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

Utilizza la --runtime per specificare l'ID runtime di un versione Ruby supportata per l'esecuzione la tua funzione.

PHP

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

Utilizza la --runtime per specificare l'ID runtime di un versione PHP supportata per l'esecuzione la tua funzione.

dove YOUR_TRIGGER_BUCKET_NAME è il nome del Bucket Cloud Storage che attiva la funzione.

Finalizzazione oggetto: attivazione della funzione

Per attivare la funzione:

  1. Crea un file gcf-test.txt vuoto nella directory in cui è visualizzato il codice campione in cui viene localizzato.

  2. Carica il file in Cloud Storage per attivare la funzione:

    gcloud storage cp gcf-test.txt gs://YOUR_TRIGGER_BUCKET_NAME
    

    dove YOUR_TRIGGER_BUCKET_NAME è il nome del tuo Bucket Cloud Storage in cui caricherai un file di test.

  3. Controlla i log per assicurarti che le esecuzioni siano state completate:

    gcloud functions logs read --limit 50
    

Eliminazione oggetto

Gli eventi di eliminazione degli oggetti sono più utili per il controllo delle versioni bucket. Vengono attivati quando viene eliminata una versione precedente di un oggetto. Inoltre, vengono attivati quando viene sovrascritto. I trigger di eliminazione degli oggetti possono essere utilizzati anche con il controllo delle versioni bucket, che si attivano quando di un oggetto viene eliminata definitivamente.

Eliminazione oggetto: deployment della funzione

Esegui il deployment della funzione utilizzando lo stesso codice campione dell'esempio finalizzato con eliminazione oggetto come evento trigger. Esegui questo comando directory in cui si trova il codice campione:

Node.js

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

Utilizza la --runtime per specificare l'ID runtime di un versione Node.js supportata per l'esecuzione la tua funzione.

Python

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

Utilizza la --runtime per specificare l'ID runtime di un versione Python supportata per l'esecuzione la tua funzione.

Vai

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

Utilizza la --runtime per specificare l'ID runtime di un versione Go supportata per l'esecuzione la tua funzione.

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

Utilizza la --runtime per specificare l'ID runtime di un versione Java supportata per l'esecuzione la tua funzione.

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

Utilizza la --runtime per specificare l'ID runtime di un versione .NET supportata per l'esecuzione la tua funzione.

Ruby

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

Utilizza la --runtime per specificare l'ID runtime di un versione Ruby supportata per l'esecuzione la tua funzione.

PHP

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

Utilizza la --runtime per specificare l'ID runtime di un versione PHP supportata per l'esecuzione la tua funzione.

dove YOUR_TRIGGER_BUCKET_NAME è il nome del Bucket Cloud Storage che attiva la funzione.

Eliminazione oggetto: attivazione della funzione

Per attivare la funzione:

  1. Crea un file gcf-test.txt vuoto nella directory in cui è visualizzato il codice campione in cui viene localizzato.

  2. Assicurati che il tuo bucket non sia sottoposto al controllo delle versioni:

    gcloud storage buckets update gs://YOUR_TRIGGER_BUCKET_NAME --no-versioning
    
  3. Carica il file su Cloud Storage:

    gcloud storage cp gcf-test.txt gs://YOUR_TRIGGER_BUCKET_NAME
    

    dove YOUR_TRIGGER_BUCKET_NAME è il nome del tuo Bucket Cloud Storage in cui caricherai un file di test. A questo punto la funzione non dovrebbe ancora essere eseguita.

  4. Elimina il file per attivare la funzione:

    gcloud storage rm gs://YOUR_TRIGGER_BUCKET_NAME/gcf-test.txt
    
  5. Controlla i log per assicurarti che le esecuzioni siano state completate:

    gcloud functions logs read --limit 50
    

Tieni presente che l'esecuzione della funzione potrebbe richiedere del tempo.

Archiviazione oggetto

Gli eventi di archiviazione degli oggetti possono essere utilizzati solo con bucket di controllo delle versioni. Sono Attivato quando viene archiviata una versione precedente di un oggetto. In particolare, significa che quando un oggetto viene sovrascritto o eliminato, un evento di archiviazione viene attivata.

Archivio oggetti: deployment della funzione

Esegui il deployment della funzione utilizzando lo stesso codice campione dell'esempio finalizzato con l'archivio di oggetti come evento trigger. Esegui questo comando directory in cui si trova il codice campione:

Node.js

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

Utilizza la --runtime per specificare l'ID runtime di un versione Node.js supportata per l'esecuzione la tua funzione.

Python

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

Utilizza la --runtime per specificare l'ID runtime di un versione Python supportata per l'esecuzione la tua funzione.

Vai

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

Utilizza la --runtime per specificare l'ID runtime di un versione Go supportata per l'esecuzione la tua funzione.

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

Utilizza la --runtime per specificare l'ID runtime di un versione Java supportata per l'esecuzione la tua funzione.

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

Utilizza la --runtime per specificare l'ID runtime di un versione .NET supportata per l'esecuzione la tua funzione.

Ruby

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

Utilizza la --runtime per specificare l'ID runtime di un versione Ruby supportata per l'esecuzione la tua funzione.

PHP

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

Utilizza la --runtime per specificare l'ID runtime di un versione PHP supportata per l'esecuzione la tua funzione.

dove YOUR_TRIGGER_BUCKET_NAME è il nome del Bucket Cloud Storage che attiva la funzione.

Archivio oggetti: attivazione della funzione

Per attivare la funzione:

  1. Crea un file gcf-test.txt vuoto nella directory in cui è visualizzato il codice campione in cui viene localizzato.

  2. Assicurati che il controllo delle versioni sia abilitato nel tuo bucket:

    gcloud storage buckets update gs://YOUR_TRIGGER_BUCKET_NAME --versioning
    
  3. Carica il file su Cloud Storage:

    gcloud storage cp gcf-test.txt gs://YOUR_TRIGGER_BUCKET_NAME
    

    dove YOUR_TRIGGER_BUCKET_NAME è il nome del tuo Bucket Cloud Storage in cui caricherai un file di test. A questo punto la funzione non dovrebbe ancora essere eseguita.

  4. Archivia il file per attivare la funzione:

    gcloud storage rm gs://YOUR_TRIGGER_BUCKET_NAME/gcf-test.txt
    
  5. Controlla i log per assicurarti che le esecuzioni siano state completate:

    gcloud functions logs read --limit 50
    

Aggiornamento metadati oggetto

Gli eventi di aggiornamento dei metadati vengono attivati quando i metadati dell'oggetto esistente vengono aggiornato.

Aggiornamento dei metadati degli oggetti: deployment della funzione

Esegui il deployment della funzione utilizzando lo stesso codice campione dell'esempio finalizzato con l'aggiornamento dei metadati come evento di trigger. Esegui questo comando directory in cui si trova il codice campione:

Node.js

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

Utilizza la --runtime per specificare l'ID runtime di un versione Node.js supportata per l'esecuzione la tua funzione.

Python

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

Utilizza la --runtime per specificare l'ID runtime di un versione Python supportata per l'esecuzione la tua funzione.

Vai

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

Utilizza la --runtime per specificare l'ID runtime di un versione Go supportata per l'esecuzione la tua funzione.

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

Utilizza la --runtime per specificare l'ID runtime di un versione Java supportata per l'esecuzione la tua funzione.

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

Utilizza la --runtime per specificare l'ID runtime di un versione .NET supportata per l'esecuzione la tua funzione.

Ruby

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

Utilizza la --runtime per specificare l'ID runtime di un versione Ruby supportata per l'esecuzione la tua funzione.

PHP

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

Utilizza la --runtime per specificare l'ID runtime di un versione PHP supportata per l'esecuzione la tua funzione.

dove YOUR_TRIGGER_BUCKET_NAME è il nome del Bucket Cloud Storage che attiva la funzione.

Aggiornamento metadati oggetto: attivazione della funzione

Per attivare la funzione:

  1. Crea un file gcf-test.txt vuoto nella directory in cui è visualizzato il codice campione in cui viene localizzato.

  2. Assicurati che il tuo bucket non sia sottoposto al controllo delle versioni:

    gcloud storage buckets update gs://YOUR_TRIGGER_BUCKET_NAME --no-versioning
    
  3. Carica il file su Cloud Storage:

    gcloud storage cp gcf-test.txt gs://YOUR_TRIGGER_BUCKET_NAME
    

    dove YOUR_TRIGGER_BUCKET_NAME è il nome del tuo Bucket Cloud Storage in cui caricherai un file di test. A questo punto la funzione non dovrebbe ancora essere eseguita.

  4. Aggiorna i metadati del file:

    gcloud storage objects update gs://YOUR_TRIGGER_BUCKET_NAME/gcf-test.txt --content-type=text/plain
    
  5. Controlla i log per assicurarti che le esecuzioni siano state completate:

    gcloud functions logs read --limit 50
    

Esegui la pulizia

Per evitare che al tuo Account Google Cloud vengano addebitati costi relativi alle risorse utilizzate in questo tutorial, elimina il progetto che contiene le risorse oppure mantieni il progetto ed elimina le singole risorse.

Elimina il progetto

Il modo più semplice per eliminare la fatturazione creato per il tutorial.

Per eliminare il progetto:

  1. Nella console Google Cloud, vai alla pagina Gestisci risorse.

    Vai a Gestisci risorse

  2. Nell'elenco dei progetti, seleziona il progetto che vuoi eliminare, quindi fai clic su Elimina.
  3. Nella finestra di dialogo, digita l'ID del progetto e fai clic su Chiudi per eliminare il progetto.

Eliminazione della Cloud Function

L'eliminazione di Cloud Functions non rimuove le risorse archiviate in Cloud Storage.

Per eliminare la Cloud Function che hai creato in questo tutorial: esegui questo comando:

Node.js

gcloud functions delete helloGCS 

Python

gcloud functions delete hello_gcs 

Vai

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 

Puoi eliminare Cloud Functions anche dalla console Google Cloud.

Passaggi successivi