Rename objects atomically

Rename objects atomically within a bucket. To rename an object, you can use the Objects: move method.

Code sample

C++

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& source_object_name,
   std::string const& destination_object_name) {
  StatusOr<gcs::ObjectMetadata> metadata = client.MoveObject(
      bucket_name, source_object_name, destination_object_name);
  if (!metadata) throw std::move(metadata).status();

  std::cout << "Successfully renamed " << source_object_name << " to "
            << destination_object_name << " in bucket " << bucket_name
            << ".\n";
}

C#

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.


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

public class MoveObjectSample
{
    /// <summary>
    /// Moves an object within a bucket with hierarchical namespace enabled.
    /// </summary>
    /// <param name="sourceBucketName">Name of the source bucket containing the object to move.</param>
    /// <param name="sourceObjectName">The name of the source object to move within the bucket.</param>
    /// <param name="destinationObjectName">The name of the new object to move to within the bucket.</param>
    public void MoveObject(
        string sourceBucketName = "source-bucket-name",
        string sourceObjectName = "source-object-name",
        string destinationObjectName = "destination-object-name")
    {
        var storage = StorageClient.Create();
        storage.MoveObject(sourceBucketName, sourceObjectName, destinationObjectName);
        Console.WriteLine($"Moved {sourceBucketName}/{sourceObjectName} to " + $"{sourceBucketName}/{destinationObjectName} within a hierarchical namespace enabled bucket.");
    }
}

Java

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.


import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.Storage.MoveBlobRequest;
import com.google.cloud.storage.StorageOptions;

public final class AtomicMoveObject {

  public static void moveObject(
      String projectId, String bucketName, String sourceObjectName, String targetObjectName) {

    // 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 sourceObjectName = "your-object-name";

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

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId source = BlobId.of(bucketName, sourceObjectName);
    BlobId target = BlobId.of(bucketName, targetObjectName);

    // Optional: set a generation-match precondition to avoid potential race
    // conditions and data corruptions. The request returns a 412 error if the
    // preconditions are not met.
    Storage.BlobTargetOption precondition;
    BlobInfo existingTarget = storage.get(target);
    if (existingTarget == null) {
      // For a target object that does not yet exist, set the DoesNotExist precondition.
      // This will cause the request to fail if the object is created before the request runs.
      precondition = Storage.BlobTargetOption.doesNotExist();
    } else {
      // If the destination already exists in your bucket, instead set a generation-match
      // precondition. This will cause the request to fail if the existing object's generation
      // changes before the request runs.
      precondition = Storage.BlobTargetOption.generationMatch(existingTarget.getGeneration());
    }

    // Atomically move source object to target object within the bucket
    MoveBlobRequest moveBlobRequest =
        MoveBlobRequest.newBuilder()
            .setSource(source)
            .setTarget(target)
            .setTargetOptions(precondition)
            .build();
    BlobInfo movedBlob = storage.moveBlob(moveBlobRequest);

    System.out.println(
        "Moved object "
            + source.toGsUtilUri()
            + " to "
            + movedBlob.getBlobId().toGsUtilUriWithGeneration());
  }
}

Node.js

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

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

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

// The new ID for your GCS file
// const destFileName = 'your-new-file-name';

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

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

async function moveFileAtomic() {
  // 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 moveOptions = {
    preconditionOpts: {
      ifGenerationMatch: destinationGenerationMatchPrecondition,
    },
  };

  // Moves the file automatically within the HNS enabled bucket
  await storage
    .bucket(bucketName)
    .file(srcFileName)
    .moveFileAtomic(destFileName, moveOptions);

  console.log(
    `gs://${bucketName}/${srcFileName} moved to gs://${bucketName}/${destFileName}`
  );
}

moveFileAtomic().catch(console.error);

PHP

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

use Google\Cloud\Storage\StorageClient;

/**
 * Move an object to a new name within HNS-enabled bucket.
 *
 * @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 $newObjectName the destination object name.
 *        (e.g. 'my-other-object')
 */
function move_object_atomic(string $bucketName, string $objectName, string $newObjectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->move($newObjectName);
    printf('Moved gs://%s/%s to gs://%s/%s' . PHP_EOL,
        $bucketName,
        $objectName,
        $bucketName,
        $newObjectName);
}

Python

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

from google.cloud import storage


def move_object(bucket_name: str, blob_name: str, new_blob_name: str) -> None:
    """Moves a blob to a new name within the same bucket using the move API."""
    # The name of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The name of your GCS object to move
    # blob_name = "your-file-name"

    # The new name of the GCS object
    # new_blob_name = "new-file-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    blob_to_move = bucket.blob(blob_name)

    # Use move_blob to perform an efficient, server-side move.
    moved_blob = bucket.move_blob(
        blob=blob_to_move, new_name=new_blob_name
    )

    print(f"Blob {blob_to_move.name} has been moved to {moved_blob.name}.")

Ruby

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

def move_object bucket_name:, source_file_name:, destination_file_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The name of your GCS object
  # source_file_name = "your-file-name"

  # The new object name which you want to craete
  # destination_file_name = "your-new-file-name"

  require "google/cloud/storage"

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

  bucket.move_file source_file_name, destination_file_name
  fetch_file = bucket.file destination_file_name
  puts "New File #{fetch_file.name} created\n"
end

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.