Changing object storage classes

This page describes how to change the storage class of objects within a bucket through rewriting the object. To learn how to change object storage classes without rewriting an object, see the Object Lifecycle Management feature.

Console

Individual object storage classes cannot be set through the Console. Instead use gsutil.

gsutil

Use the -s flag in a rewrite command. For example:

gsutil rewrite -s STORAGE_CLASS gs://PATH_TO_OBJECT

Where:

  • STORAGE_CLASS is the new storage class for your object. For example, nearline.
  • PATH_TO_OBJECT is the name of the object whose class you want to change. For example, pets/dog.png.

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

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::runtime_error(object_metadata.status().message());
  }

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

Go

For more information, see the Cloud Storage Go API reference documentation.

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: %v", err)
	}
	defer client.Close()

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

	bkt := client.Bucket(bucket)
	obj := bkt.Object(object)
	// 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 := obj.CopierFrom(obj)
	copier.StorageClass = newStorageClass
	if _, err := copier.Run(ctx); err != nil {
		return fmt.Errorf("copier.Run: %v", err)
	}
	fmt.Fprintf(w, "Object %v in bucket %v had its storage class set to %v\n", object, bucket, newStorageClass)
	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

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

    // 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
    Storage.CopyRequest request =
        Storage.CopyRequest.newBuilder()
            .setSource(blobId)
            .setTarget(BlobInfo.newBuilder(blobId).setStorageClass(storageClass).build())
            .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

For more information, see the Cloud Storage Node.js API reference documentation.

// 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.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const fileName = 'File to access, e.g. file.txt';
// const storageClass = 'Name of a storage class, e.g. standard';
async function fileChangeStorageClass() {
  await storage
    .bucket(bucketName)
    .file(fileName)
    .setStorageClass(storageClass);

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

fileChangeStorageClass();

Python

For more information, see the Cloud Storage Python API reference documentation.

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.get_bucket(bucket_name)
    blob = bucket.get_blob(blob_name)
    blob.update_storage_class("NEARLINE")

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

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

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

  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

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that contains the following information:

    {
      "storageClass": "STORAGE_CLASS"
    }

    Where:

    • STORAGE_CLASS is the new storage class for your object. For example, nearline.
  3. Use cURL to call the JSON API with a POST Object, request:

    curl -X POST --data-binary @JSON_FILE_NAME.json \
      -H "Authorization: Bearer OAUTH2_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"

    Where:

    • JSON_FILE_NAME is the name of the JSON file you created in Step 2.
    • OAUTH2_TOKEN is the access token you generated in Step 1.
    • BUCKET_NAME is the name of the bucket containing the original object. For example, my-bucket.
    • OBJECT_NAME is the name of the object. For example, pets/dog.png.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the XML API with a PUT Object request:

    curl -X PUT --data-binary @OBJECT \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: OBJECT_CONTENT_TYPE" \
      -H "x-goog-storage-class: STORAGE_CLASS" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    Where:

    • OBJECT is the local path to the object whose storage class you want to change (you must re-upload the object when changing storage class with the XML API). For example, Desktop/dog.png.
    • OAUTH2_TOKEN is the access token you generated in Step 1.
    • OBJECT_CONTENT_TYPE is the content type of the object. For example, image/png.
    • STORAGE_CLASS is the new storage class for your object. For example, nearline.
    • BUCKET_NAME is the name of the bucket containing the object you are rewriting. For example, my-bucket.
    • OBJECT_NAME is the name of the object you are rewriting. For example, pets/dog.png.

What's next