Modificare le classi di archiviazione degli oggetti

In questa pagina viene descritto come modificare la classe di archiviazione degli oggetti all'interno di un bucket mediante la riscrittura dell'oggetto.

  • Per informazioni su come modificare le classi di archiviazione degli oggetti senza riscrivere un oggetto, consulta la funzionalità Gestione del ciclo di vita degli oggetti.
  • Per scoprire come Cloud Storage può gestire automaticamente le classi di archiviazione del tuo oggetto, consulta la funzionalità Autoclass.

Ruoli obbligatori

Per ottenere le autorizzazioni necessarie per modificare la classe di archiviazione di un oggetto mediante la riscrittura dell'oggetto, chiedi all'amministratore di concederti il ruolo Utente oggetti Storage (roles/storage.objectUser) nel bucket.

Questo ruolo contiene le autorizzazioni necessarie per modificare la classe di archiviazione di un oggetto. Per visualizzare esattamente le autorizzazioni richieste, espandi la sezione Autorizzazioni obbligatorie:

Autorizzazioni obbligatorie

  • storage.objects.create
  • storage.objects.delete
  • storage.objects.get
  • storage.objects.list

Potresti anche riuscire a ottenere queste autorizzazioni con altri ruoli predefiniti o ruoli personalizzati.

Per istruzioni sulla concessione dei ruoli sui bucket, consulta Utilizzare IAM con i bucket.

Modifica della classe di archiviazione di un oggetto

Per modificare la classe di archiviazione di un oggetto:

Console

Non è possibile impostare classi di archiviazione di singoli oggetti tramite la console Google Cloud. Utilizza invece Google Cloud CLI.

Riga di comando

Utilizza il comando gcloud storage objects update con il flag --storage-class. Ad esempio:

gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME --storage-class=STORAGE_CLASS

Dove:

  • BUCKET_NAME è il nome del bucket che contiene l'oggetto di cui vuoi modificare la classe. Ad esempio, my-bucket.
  • OBJECT_NAME è il nome dell'oggetto di cui vuoi modificare la classe. Ad esempio, pets/dog.png.
  • STORAGE_CLASS è la nuova classe di archiviazione per l'oggetto. Ad esempio: nearline.

Librerie client

C++

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& storage_class) {
  StatusOr<gcs::ObjectMetadata> object_metadata =
      client.RewriteObjectBlocking(
          bucket_name, object_name, bucket_name, object_name,
          gcs::WithObjectMetadata(
              gcs::ObjectMetadata().set_storage_class(storage_class)));
  if (!object_metadata) throw std::move(object_metadata).status();

  std::cout << "Changed storage class of object " << object_metadata->name()
            << " in bucket " << object_metadata->bucket() << " to "
            << object_metadata->storage_class() << "\n";
}

C#

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


using Google.Cloud.Storage.V1;
using System;

public class ChangeFileStorageClassSample
{
    public Google.Apis.Storage.v1.Data.Object ChangeFileStorageClass(
        string bucketName = "your-bucket-name",
        string objectName = "your-object-name",
        string storageClass = StorageClasses.Standard)
    {
        var storage = StorageClient.Create();

        // Changing storage class requires a rewrite operation, which can only be done
        // by the underlying service
        var obj = new Google.Apis.Storage.v1.Data.Object { StorageClass = storageClass };
        storage.Service.Objects.Rewrite(obj, bucketName, objectName, bucketName, objectName).Execute();

        var file = storage.GetObject(bucketName, objectName);
        Console.WriteLine($"Object {objectName} in bucket {bucketName} had" +
            $" its storage class set to {storageClass}.");

        return file;
    }
}

Go

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// changeObjectStorageClass changes the storage class of a single object.
func changeObjectStorageClass(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	o := client.Bucket(bucket).Object(object)

	// Optional: set a generation-match precondition to avoid potential race
	// conditions and data corruptions. The request to copy is aborted if the
	// object's generation number does not match your precondition.
	attrs, err := o.Attrs(ctx)
	if err != nil {
		return fmt.Errorf("object.Attrs: %w", err)
	}
	o = o.If(storage.Conditions{GenerationMatch: attrs.Generation})

	// See the StorageClass documentation for other valid storage classes:
	// https://cloud.google.com/storage/docs/storage-classes
	newStorageClass := "COLDLINE"
	// You can't change an object's storage class directly, the only way is
	// to rewrite the object with the desired storage class.
	copier := o.CopierFrom(o)
	copier.StorageClass = newStorageClass
	if _, err := copier.Run(ctx); err != nil {
		return fmt.Errorf("copier.Run: %w", err)
	}
	fmt.Fprintf(w, "Object %v in bucket %v had its storage class set to %v\n", object, bucket, newStorageClass)
	return nil
}

Java

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageClass;
import com.google.cloud.storage.StorageOptions;

public class ChangeObjectStorageClass {
  public static void changeObjectStorageClass(
      String projectId, String bucketName, String objectName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, objectName);
    Blob sourceBlob = storage.get(blobId);
    if (sourceBlob == null) {
      System.out.println("The object " + objectName + " wasn't found in " + bucketName);
      return;
    }

    // See the StorageClass documentation for other valid storage classes:
    // https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/StorageClass.html
    StorageClass storageClass = StorageClass.COLDLINE;

    // You can't change an object's storage class directly, the only way is to rewrite the object
    // with the desired storage class

    BlobInfo targetBlob = BlobInfo.newBuilder(blobId).setStorageClass(storageClass).build();

    // Optional: set a generation-match precondition to avoid potential race
    // conditions and data corruptions. The request to upload returns a 412 error if
    // the object's generation number does not match your precondition.
    Storage.BlobSourceOption precondition =
        Storage.BlobSourceOption.generationMatch(sourceBlob.getGeneration());

    Storage.CopyRequest request =
        Storage.CopyRequest.newBuilder()
            .setSource(blobId)
            .setSourceOptions(precondition) // delete this line to run without preconditions
            .setTarget(targetBlob)
            .build();
    Blob updatedBlob = storage.copy(request).getResult();

    System.out.println(
        "Object "
            + objectName
            + " in bucket "
            + bucketName
            + " had its storage class set to "
            + updatedBlob.getStorageClass().name());
  }
}

Node.js

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const fileName = 'your-file-name';

// The name of a storage class
// See the StorageClass documentation for other valid storage classes:
// https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/StorageClass.html
// const storageClass = 'coldline';

async function fileChangeStorageClass() {
  // Optional:
  // Set a generation-match precondition to avoid potential race conditions
  // and data corruptions. The request to copy is aborted if the object's
  // generation number does not match your precondition. For a destination
  // object that does not yet exist, set the ifGenerationMatch precondition to 0
  // If the destination object already exists in your bucket, set instead a
  // generation-match precondition using its generation number.
  const setStorageClassOptions = {
    ifGenerationMatch: generationMatchPrecondition,
  };

  await storage
    .bucket(bucketName)
    .file(fileName)
    .setStorageClass(storageClass, setStorageClassOptions);

  console.log(`${fileName} has been set to ${storageClass}`);
}

fileChangeStorageClass().catch(console.error);

PHP

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

use Google\Cloud\Storage\StorageClient;

/**
 * Change the storage class of the given file.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $storageClass The storage class of the new object.
 *        (e.g. 'COLDLINE')
 */
function change_file_storage_class(string $bucketName, string $objectName, string $storageClass): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);

    // Storage class cannot be changed directly. But we can rewrite the object
    // using the new storage class.

    $newObject = $object->rewrite($bucket, [
        'storageClass' => $storageClass,
    ]);

    printf(
        'Object %s in bucket %s had its storage class set to %s',
        $objectName,
        $bucketName,
        $newObject->info()['storageClass']
    );
}

Python

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

from google.cloud import storage


def change_file_storage_class(bucket_name, blob_name):
    """Change the default storage class of the blob"""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)
    generation_match_precondition = None

    # Optional: set a generation-match precondition to avoid potential race
    # conditions and data corruptions. The request is aborted if the
    # object's generation number does not match your precondition.
    blob.reload()  # Fetch blob metadata to use in generation_match_precondition.
    generation_match_precondition = blob.generation

    blob.update_storage_class("NEARLINE", if_generation_match=generation_match_precondition)

    print(
        "Blob {} in bucket {} had its storage class set to {}".format(
            blob_name,
            bucket_name,
            blob.storage_class
        )
    )
    return blob

Ruby

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Ruby di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

def change_file_storage_class bucket_name:, file_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name, skip_lookup: true

  file = bucket.file file_name

  file.storage_class = "NEARLINE"

  puts "File #{file_name} in bucket #{bucket_name} had its storage class set to #{file.storage_class}"
end

API REST

API JSON

  1. Installa e inizializzatogcloud CLI per generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Crea un file JSON contenente le seguenti informazioni:

    {
      "storageClass": "STORAGE_CLASS"
    }

    Dove:

  3. Utilizza cURL per chiamare l'API JSON con un oggetto POST, richiesta:

    curl -X POST --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME/rewriteTo/b/BUCKET_NAME/o/OBJECT_NAME"

    Dove:

    • JSON_FILE_NAME è il percorso del file JSON creato al passaggio 2.
    • BUCKET_NAME è il nome del bucket che contiene l'oggetto originale. Ad esempio, my-bucket.
    • OBJECT_NAME è il nome dell'oggetto con codifica URL. Ad esempio, pets/dog.png, con codifica URL pets%2Fdog.png.

API XML

  1. Installa e inizializzatogcloud CLI per generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Utilizza cURL per chiamare l'API XML con una richiesta Oggetto PUT:

    curl -X PUT --data-binary @OBJECT \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: OBJECT_CONTENT_TYPE" \
      -H "x-goog-storage-class: STORAGE_CLASS" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    Dove:

    • OBJECT è il percorso locale dell'oggetto di cui vuoi modificare la classe di archiviazione (devi ricaricare l'oggetto quando modifichi la classe di archiviazione con l'API XML). Ad esempio, Desktop/dog.png.
    • OBJECT_CONTENT_TYPE è il tipo di contenuto dell'oggetto. Ad esempio: image/png.
    • STORAGE_CLASS è la nuova classe di archiviazione per il tuo oggetto. Ad esempio: nearline.
    • BUCKET_NAME è il nome del bucket contenente l'oggetto che stai riscrivendo. Ad esempio, my-bucket.
    • OBJECT_NAME è il nome con codifica URL dell'oggetto che stai riscrivendo. Ad esempio, pets/dog.png, con codifica URL come pets%2Fdog.png.

Passaggi successivi