객체 복사, 이름 바꾸기, 이동

이 페이지에서는 객체를 복사하고, 객체의 이름을 바꾸고, 객체를 이동하는 방법을 설명합니다. 일부 도구는 원자적 객체 이동 작업을 수행하지만 다른 도구는 객체를 새로 지정된 위치로 복사한 다음 원본 객체를 삭제하여 객체 이동 작업을 시뮬레이션합니다.

Storage Transfer Service를 사용하여 버킷 간에 데이터를 1TB 이상 이동하는 것이 좋습니다.

시작하기 전에

객체를 복사, 이름 바꾸기 또는 이동하려면 필요한 IAM 역할을 획득해야 합니다. 다음 섹션에서는 다양한 사용 사례에 대한 IAM 요구사항을 설명합니다.

객체 복사(복사를 통한 이동 또는 이름 바꾸기 포함)

객체를 복사하는 데 필요한 권한을 얻으려면 관리자에게 이동할 객체가 포함된 소스 버킷 또는 객체를 이동할 대상 버킷에 대해 다음 IAM 역할을 부여해 달라고 요청하세요.

  • 소스 버킷의 스토리지 객체 뷰어(roles/storage.objectViewer)
  • 대상 버킷의 스토리지 객체 사용자(roles/storage.objectUser)
  • Google Cloud 콘솔을 사용하여 객체를 복사하려면 roles/storage.objectViewerroles/storage.objectUser 외에도 소스 버킷과 대상 버킷 모두에 뷰어 기본 역할(roles/viewer)이 있어야 합니다.

이러한 사전 정의된 역할에는 객체를 복사하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 펼치세요.

필수 권한

객체를 복사하려면 다음 권한이 필요합니다.

  • 소스 버킷에 대한 storage.objects.get
  • 대상 버킷에 대한 storage.objects.create
  • 대상 버킷에 대한 storage.objects.delete(객체 복사 또는 이동 작업의 일부로 대상 버킷에서 객체를 교체하거나 덮어쓰는 경우에만 필요)
  • 소스 버킷에 대한 storage.objects.delete(기본 복사 및 삭제 작업을 사용하여 객체를 이동하는 경우에만 필요)
  • 대상 버킷에 대한 storage.folders.create(이동하려는 객체가 대상 버킷에 만들려는 폴더에 있는 경우에만 필요)
  • 소스 및 대상 버킷에 대한 storage.objects.list( Google Cloud 콘솔을 사용하여 객체를 복사, 이동 또는 이름 변경하는 경우에만 필요)
  • 소스 및 대상 버킷이 포함된 프로젝트에 대한 storage.buckets.list( Google Cloud 콘솔을 사용하여 객체를 복사, 이동 또는 이름 변경하는 경우에만 필요)

커스텀 역할로도 이러한 권한을 얻을 수 있습니다.

버킷의 역할 부여에 대한 자세한 내용은 버킷에 IAM 사용을 참조하세요. 프로젝트에 대해 역할을 부여하는 방법은 프로젝트에 대한 액세스 관리를 참조하세요.

복사하려는 객체에 특정 기능이 사용 설정되어 있는 경우 추가 역할이나 대체 역할이 필요할 수 있습니다. 예를 들어 복사하려는 객체에 보관하려는 객체 보관 구성이 있는 경우 스토리지 객체 관리자(roles/storage.objectAdmin) 역할과 같이 storage.objects.setRetention 권한이 포함된 대상 버킷의 역할이 필요합니다. 자세한 내용은 Cloud Storage의 IAM 권한을 참조하세요.

원자적으로 객체 이름 바꾸기

객체의 이름을 원자적으로 바꾸는 데 필요한 권한을 얻으려면 관리자에게 이름을 바꿀 객체가 포함된 버킷에 대한 스토리지 객체 사용자(roles/storage.objectUser) IAM 역할을 부여해 달라고 요청하세요.

이 사전 정의된 역할에는 객체의 이름을 원자적으로 변경하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 펼치세요.

필수 권한

객체의 이름을 원자적으로 바꾸려면 다음 권한이 필요합니다.

  • storage.objects.move
  • storage.objects.create
  • storage.objects.delete(객체를 덮어쓰거나 대체하는 경우에만 필요)

커스텀 역할로도 이러한 권한을 얻을 수 있습니다.

버킷의 역할 부여에 대한 자세한 내용은 버킷에 IAM 사용을 참조하세요.

객체 복사

이 섹션에서는 객체를 복사하는 방법을 설명합니다. 한 버킷에서 다른 버킷으로 객체를 복사할 수 있습니다.

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 복사하려는 객체가 포함된 버킷 이름을 클릭합니다.

    객체 탭이 선택된 상태로 버킷 세부정보 페이지가 열립니다.

  3. 객체(폴더에 있을 수 있음)로 이동합니다.

  4. 객체와 연결된 객체 오버플로 메뉴()를 클릭합니다.

  5. 복사를 클릭합니다.

    객체 복사 창이 나타납니다.

  6. 대상 필드에 대상 버킷의 이름과 복사된 객체의 이름을 입력합니다.

    또는 둘러보기를 클릭하여 대상을 선택할 수 있지만 둘러보기 옵션은 현재 프로젝트의 버킷으로 제한됩니다.

  7. 복사를 클릭합니다.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

gcloud storage cp 명령어를 사용합니다.

gcloud storage cp gs://SOURCE_BUCKET_NAME/SOURCE_OBJECT_NAME gs://DESTINATION_BUCKET_NAME/NAME_OF_COPY

각 항목의 의미는 다음과 같습니다.

  • SOURCE_BUCKET_NAME은 복사할 객체가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.
  • SOURCE_OBJECT_NAME은 복사할 객체의 이름입니다. 예를 들면 pets/dog.png입니다.
  • DESTINATION_BUCKET_NAME은 객체를 복사할 버킷의 이름입니다. 예를 들면 another-bucket입니다.
  • NAME_OF_COPY는 객체의 사본에 지정할 이름입니다. 예를 들면 shiba.png입니다.

성공하면 다음 예시와 비슷한 응답이 표시됩니다.

Copying gs://example-bucket/file.txt to gs://other-bucket/file-copy.txt
  Completed files 1/1 | 164.3kiB/164.3kiB 

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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

  std::cout << "Successfully copied " << source_object_name << " in bucket "
            << source_bucket_name << " to bucket " << new_copy_meta->bucket()
            << " with name " << new_copy_meta->name()
            << ".\nThe full metadata after the copy is: " << *new_copy_meta
            << "\n";
}

C#

자세한 내용은 Cloud Storage C# API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.


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

public class CopyFileSample
{
    public void CopyFile(
        string sourceBucketName = "source-bucket-name",
        string sourceObjectName = "source-file",
        string destBucketName = "destination-bucket-name",
        string destObjectName = "destination-file-name")
    {
        var storage = StorageClient.Create();
        storage.CopyObject(sourceBucketName, sourceObjectName, destBucketName, destObjectName);

        Console.WriteLine($"Copied {sourceBucketName}/{sourceObjectName} to " + $"{destBucketName}/{destObjectName}.");
    }
}

Go

자세한 내용은 Cloud Storage Go API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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

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

// copyFile copies an object into specified bucket.
func copyFile(w io.Writer, dstBucket, srcBucket, srcObject string) error {
	// dstBucket := "bucket-1"
	// srcBucket := "bucket-2"
	// srcObject := "object"
	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()

	dstObject := srcObject + "-copy"
	src := client.Bucket(srcBucket).Object(srcObject)
	dst := client.Bucket(dstBucket).Object(dstObject)

	// 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 dst object that does not yet exist, set the DoesNotExist precondition.
	dst = dst.If(storage.Conditions{DoesNotExist: true})
	// If the destination object already exists in your bucket, set instead a
	// generation-match precondition using its generation number.
	// attrs, err := dst.Attrs(ctx)
	// if err != nil {
	// 	return fmt.Errorf("object.Attrs: %w", err)
	// }
	// dst = dst.If(storage.Conditions{GenerationMatch: attrs.Generation})

	if _, err := dst.CopierFrom(src).Run(ctx); err != nil {
		return fmt.Errorf("Object(%q).CopierFrom(%q).Run: %w", dstObject, srcObject, err)
	}
	fmt.Fprintf(w, "Blob %v in bucket %v copied to blob %v in bucket %v.\n", srcObject, srcBucket, dstObject, dstBucket)
	return nil
}

Java

자세한 내용은 Cloud Storage Java API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.


import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.CopyWriter;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.Storage.CopyRequest;
import com.google.cloud.storage.StorageOptions;

public class CopyObject {
  public static void copyObject(
      String projectId, String sourceBucketName, String objectName, String targetBucketName)
      throws Exception {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of the bucket the original object is in
    // String sourceBucketName = "your-source-bucket";

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

    // The ID of the bucket to copy the object to
    // String targetBucketName = "target-object-bucket";

    try (Storage storage =
        StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
      BlobId sourceId = BlobId.of(sourceBucketName, objectName);
      // you could change "objectName" to rename the object
      BlobId targetId = BlobId.of(targetBucketName, objectName);

      // Recommended: 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(targetBucketName, objectName);
      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());
      }

      CopyRequest copyRequest =
          CopyRequest.newBuilder()
              .setSource(sourceId)
              .setTarget(targetId, precondition)
              // limit the number of bytes Cloud Storage will attempt to copy before responding to
              // an individual request.
              // If you see Read Timeout errors, try reducing this value.
              .setMegabytesCopiedPerChunk(2048L) // 2GiB
              .build();
      CopyWriter copyWriter = storage.copy(copyRequest);
      BlobInfo successfulCopyResult = copyWriter.getResult();

      System.out.printf(
          "Copied object gs://%s/%s to %s%n",
          sourceBucketName,
          objectName,
          successfulCopyResult.getBlobId().toGsUtilUriWithGeneration());
    }
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of the bucket the original file is in
// const srcBucketName = 'your-source-bucket';

// The ID of the GCS file to copy
// const srcFilename = 'your-file-name';

// The ID of the bucket to copy the file to
// const destBucketName = 'target-file-bucket';

// The ID of the GCS file to create
// const destFileName = 'target-file-name';

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

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

async function copyFile() {
  const copyDestination = storage.bucket(destBucketName).file(destFileName);

  // 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 copyOptions = {
    preconditionOpts: {
      ifGenerationMatch: destinationGenerationMatchPrecondition,
    },
  };

  // Copies the file to the other bucket
  await storage
    .bucket(srcBucketName)
    .file(srcFilename)
    .copy(copyDestination, copyOptions);

  console.log(
    `gs://${srcBucketName}/${srcFilename} copied to gs://${destBucketName}/${destFileName}`
  );
}

copyFile().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

use Google\Cloud\Storage\StorageClient;

/**
 * Copy an object to a new name and/or 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 $newBucketName The destination bucket name.
 *        (e.g. 'my-other-bucket')
 * @param string $newObjectName The destination object name.
 *        (e.g. 'my-other-object')
 */
function copy_object(string $bucketName, string $objectName, string $newBucketName, string $newObjectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->copy($newBucketName, ['name' => $newObjectName]);
    printf('Copied gs://%s/%s to gs://%s/%s' . PHP_EOL,
        $bucketName, $objectName, $newBucketName, $newObjectName);
}

Python

자세한 내용은 Cloud Storage Python API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

from google.cloud import storage


def copy_blob(
    bucket_name, blob_name, destination_bucket_name, destination_blob_name,
):
    """Copies a blob from one bucket to another with a new name."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"
    # destination_bucket_name = "destination-bucket-name"
    # destination_blob_name = "destination-object-name"

    storage_client = storage.Client()

    source_bucket = storage_client.bucket(bucket_name)
    source_blob = source_bucket.blob(blob_name)
    destination_bucket = storage_client.bucket(destination_bucket_name)

    # 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 if_generation_match precondition to 0.
    # If the destination object already exists in your bucket, set instead a
    # generation-match precondition using its generation number.
    # There is also an `if_source_generation_match` parameter, which is not used in this example.
    destination_generation_match_precondition = 0

    blob_copy = source_bucket.copy_blob(
        source_blob, destination_bucket, destination_blob_name, if_generation_match=destination_generation_match_precondition,
    )

    print(
        "Blob {} in bucket {} copied to blob {} in bucket {}.".format(
            source_blob.name,
            source_bucket.name,
            blob_copy.name,
            destination_bucket.name,
        )
    )

Ruby

자세한 내용은 Cloud Storage Ruby API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

def copy_file source_bucket_name:, source_file_name:, destination_bucket_name:, destination_file_name:
  # The ID of the bucket the original object is in
  # source_bucket_name = "source-bucket-name"

  # The ID of the GCS object to copy
  # source_file_name = "source-file-name"

  # The ID of the bucket to copy the object to
  # destination_bucket_name = "destination-bucket-name"

  # The ID of the new GCS object
  # destination_file_name = "destination-file-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket source_bucket_name, skip_lookup: true
  file    = bucket.file source_file_name

  destination_bucket = storage.bucket destination_bucket_name
  destination_file   = file.copy destination_bucket.name, destination_file_name

  puts "#{file.name} in #{bucket.name} copied to " \
       "#{destination_file.name} in #{destination_bucket.name}"
end

REST API

JSON API

  1. Authorization 헤더에 대한 액세스 토큰을 생성하려면 gcloud CLI가 설치 및 초기화되어 있어야 합니다.

  2. cURL을 사용하여 POST 객체 요청으로 JSON API를 호출합니다.

    curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Length: 0" \
      "https://storage.googleapis.com/storage/v1/b/SOURCE_BUCKET_NAME/o/SOURCE_OBJECT_NAME/rewriteTo/b/DESTINATION_BUCKET_NAME/o/NAME_OF_COPY"

    각 항목의 의미는 다음과 같습니다.

    • SOURCE_BUCKET_NAME은 복사할 객체가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • SOURCE_OBJECT_NAME은 복사할 객체의 URL 인코딩 이름입니다. 예를 들어 pets/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.
    • DESTINATION_BUCKET_NAME은 객체를 복사할 버킷의 이름입니다. 예를 들면 another-bucket입니다.
    • NAME_OF_COPY은 객체의 사본에 지정할 URL로 인코딩된 이름입니다. 예를 들면 shiba.png입니다.

    rewrite 메서드는 제한된 크기의 청크로 데이터를 복사하므로 특히 큰 객체의 경우 복사본에 여러 개의 요청이 필요할 수 있습니다.

    예를 들어 rewrite 요청에 다음과 같은 응답이 반환되면 추가 rewrite 요청을 수행해야 한다는 의미입니다.

    {
      "kind": "storage#rewriteResponse",
      "totalBytesRewritten": 1048576,
      "objectSize": 10000000000,
      "done": false,
      "rewriteToken": TOKEN_VALUE
    }
  3. 이후 요청에서 rewriteToken을 사용하여 데이터를 계속 복사합니다.

    curl -X POST \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Length: 0" \
     -d '{"rewriteToken": "TOKEN_VALUE"}' \
     "https://storage.googleapis.com/storage/v1/b/SOURCE_BUCKET_NAME/o/SOURCE_OBJECT_NAME/rewriteTo/b/DESTINATION_BUCKET_NAME/o/NAME_OF_COPY"

    각 항목의 의미는 다음과 같습니다.

    • TOKEN_VALUE는 이전 요청에서 반환된 rewriteToken 값입니다.
    • 다른 모든 값은 이전 요청에서 사용된 값과 일치합니다.

    객체가 완전히 복사되면 마지막 응답에 true(으)로 설정된 done 속성이 있고 rewriteToken 속성은 없으며 resource 속성에 복사본의 메타데이터가 포함됩니다.

    {
     "kind": "storage#rewriteResponse",
     "totalBytesRewritten": 10000000000,
     "objectSize": 10000000000,
     "done": true,
     "resource": objects Resource
    }

XML API

  1. Authorization 헤더에 대한 액세스 토큰을 생성하려면 gcloud CLI가 설치 및 초기화되어 있어야 합니다.

  2. cURL을 사용하여 PUT 객체 요청으로 XML API를 호출합니다.

    curl -X PUT \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "x-goog-copy-source: SOURCE_BUCKET_NAME/SOURCE_OBJECT_NAME" \
      "https://storage.googleapis.com/DESTINATION_BUCKET_NAME/NAME_OF_COPY"

    각 항목의 의미는 다음과 같습니다.

    • SOURCE_BUCKET_NAME은 복사할 객체가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • SOURCE_OBJECT_NAME은 복사할 객체의 이름입니다. 예를 들면 pets/dog.png입니다.
    • DESTINATION_BUCKET_NAME은 객체를 복사할 버킷의 이름입니다. 예를 들면 another-bucket입니다.
    • NAME_OF_COPY은 객체의 사본에 지정할 URL로 인코딩된 이름입니다. 예를 들면 shiba.png입니다.

복사하여 객체 이동 또는 이름 바꾸기

이 섹션에서는 기본 객체 복사 작업을 사용하여 객체를 이동하거나 이름을 바꾸는 방법을 설명합니다. 이 섹션에 설명된 도구는 원래 객체를 다른 네임스페이스로 복사한 다음 원래 객체를 삭제하여 객체를 이동하고 이름을 바꿉니다.

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 이동할 객체가 포함된 버킷의 이름을 클릭합니다.

    객체 탭이 선택된 상태로 버킷 세부정보 페이지가 열립니다.

  3. 객체(폴더에 있을 수 있음)로 이동합니다.

  4. 객체와 연결된 객체 오버플로 메뉴()를 클릭합니다.

  5. 동일한 버킷에 객체 이름을 새로 지정하려면 이름 바꾸기를 클릭합니다.

    1. 나타나는 오버레이 창에서 객체의 새 이름을 입력합니다.

    2. 이름 바꾸기를 클릭합니다.

  6. 객체를 다른 버킷으로 이동하려면 이동을 클릭합니다.

    1. 오버레이 창이 나타나면 찾아보기를 클릭합니다.

    2. 이동할 객체의 대상 위치를 선택합니다.

    3. 선택을 클릭합니다.

    4. 이동을 클릭합니다.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

gcloud storage mv 명령어를 사용합니다.

gcloud storage mv gs://SOURCE_BUCKET_NAME/SOURCE_OBJECT_NAME gs://DESTINATION_BUCKET_NAME/DESTINATION_OBJECT_NAME

각 항목의 의미는 다음과 같습니다.

  • SOURCE_BUCKET_NAME은 이동하거나 이름을 변경할 객체가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.
  • SOURCE_OBJECT_NAME은 이동하거나 이름을 바꿀 객체의 이름입니다. 예를 들면 pets/dog.png입니다.
  • DESTINATION_BUCKET_NAME은 객체를 이동할 버킷의 이름입니다. 예를 들면 another-bucket입니다.
  • DESTINATION_OBJECT_NAME은 이동하거나 이름이 변경된 객체에 지정할 이름입니다. 예를 들면 shiba.png입니다.

성공하면 다음 예시와 비슷한 응답이 표시됩니다.

Copying gs://example-bucket/old-file.txt to gs://new-bucket/new-file.txt
Removing gs://example-bucket/old-file.txt...
  Completed files 1/1 | 164.3kiB/164.3kiB 

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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

  google::cloud::Status status =
      client.DeleteObject(bucket_name, old_object_name);
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "Renamed " << old_object_name << " to " << new_object_name
            << " in bucket " << bucket_name << "\n";
}

C#

자세한 내용은 Cloud Storage C# API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.


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

public class MoveFileSample
{
    public void MoveFile(
        string sourceBucketName = "your-unique-bucket-name",
        string sourceObjectName = "your-object-name",
        string targetBucketName = "target-object-bucket",
        string targetObjectName = "target-object-name")
    {
        var storage = StorageClient.Create();
        storage.CopyObject(sourceBucketName, sourceObjectName, targetBucketName, targetObjectName);
        storage.DeleteObject(sourceBucketName, sourceObjectName);
        Console.WriteLine($"Moved {sourceObjectName} to {targetObjectName}.");
    }
}

Go

자세한 내용은 Cloud Storage Go API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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

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

// moveFile moves an object into another location.
func moveFile(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()

	dstName := object + "-rename"
	src := client.Bucket(bucket).Object(object)
	dst := client.Bucket(bucket).Object(dstName)

	// Optional: set a generation-match precondition to avoid potential race
	// conditions and data corruptions. The request to copy the file is aborted
	// if the object's generation number does not match your precondition.
	// For a dst object that does not yet exist, set the DoesNotExist precondition.
	dst = dst.If(storage.Conditions{DoesNotExist: true})
	// If the destination object already exists in your bucket, set instead a
	// generation-match precondition using its generation number.
	// attrs, err := dst.Attrs(ctx)
	// if err != nil {
	// 	return fmt.Errorf("object.Attrs: %w", err)
	// }
	// dst = dst.If(storage.Conditions{GenerationMatch: attrs.Generation})

	if _, err := dst.CopierFrom(src).Run(ctx); err != nil {
		return fmt.Errorf("Object(%q).CopierFrom(%q).Run: %w", dstName, object, err)
	}
	if err := src.Delete(ctx); err != nil {
		return fmt.Errorf("Object(%q).Delete: %w", object, err)
	}
	fmt.Fprintf(w, "Blob %v moved to %v.\n", object, dstName)
	return nil
}

Java

자세한 내용은 Cloud Storage Java API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.


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.StorageOptions;

public class CopyDeleteObject {
  public static void copyDeleteObject(
      String projectId,
      String sourceBucketName,
      String sourceObjectName,
      String targetBucketName,
      String targetObjectName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

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

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

    // The ID of the bucket to move the object objectName to
    // String targetBucketName = "target-object-bucket"

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

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId source = BlobId.of(sourceBucketName, sourceObjectName);
    BlobId target = BlobId.of(targetBucketName, 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(targetBucketName, targetObjectName);
    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());
    }

    // Copy source object to target object
    storage.copy(
        Storage.CopyRequest.newBuilder().setSource(source).setTarget(target, precondition).build());
    Blob copiedObject = storage.get(target);
    // Delete the original blob now that we've copied to where we want it, finishing the "move"
    // operation
    storage.get(source).delete();

    System.out.println(
        "Moved object "
            + sourceObjectName
            + " from bucket "
            + sourceBucketName
            + " to "
            + targetObjectName
            + " in bucket "
            + copiedObject.getBucket());
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

/**
 * 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 moveFile() {
  // 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 within the bucket
  await storage
    .bucket(bucketName)
    .file(srcFileName)
    .move(destFileName, moveOptions);

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

moveFile().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

use Google\Cloud\Storage\StorageClient;

/**
 * Move an object to a new name and/or 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 $newBucketName the destination bucket name.
 *        (e.g. 'my-other-bucket')
 * @param string $newObjectName the destination object name.
 *        (e.g. 'my-other-object')
 */
function move_object(string $bucketName, string $objectName, string $newBucketName, string $newObjectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->copy($newBucketName, ['name' => $newObjectName]);
    $object->delete();
    printf('Moved gs://%s/%s to gs://%s/%s' . PHP_EOL,
        $bucketName,
        $objectName,
        $newBucketName,
        $newObjectName);
}

Python

자세한 내용은 Cloud Storage Python API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

from google.cloud import storage


def move_blob(bucket_name, blob_name, destination_bucket_name, destination_blob_name,):
    """Moves a blob from one bucket to another with a new name."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The ID of your GCS object
    # blob_name = "your-object-name"
    # The ID of the bucket to move the object to
    # destination_bucket_name = "destination-bucket-name"
    # The ID of your new GCS object (optional)
    # destination_blob_name = "destination-object-name"

    storage_client = storage.Client()

    source_bucket = storage_client.bucket(bucket_name)
    source_blob = source_bucket.blob(blob_name)
    destination_bucket = storage_client.bucket(destination_bucket_name)

    # 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. For a destination
    # object that does not yet exist, set the if_generation_match precondition to 0.
    # If the destination object already exists in your bucket, set instead a
    # generation-match precondition using its generation number.
    # There is also an `if_source_generation_match` parameter, which is not used in this example.
    destination_generation_match_precondition = 0

    blob_copy = source_bucket.copy_blob(
        source_blob, destination_bucket, destination_blob_name, if_generation_match=destination_generation_match_precondition,
    )
    source_bucket.delete_blob(blob_name)

    print(
        "Blob {} in bucket {} moved to blob {} in bucket {}.".format(
            source_blob.name,
            source_bucket.name,
            blob_copy.name,
            destination_bucket.name,
        )
    )

Ruby

자세한 내용은 Cloud Storage Ruby API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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

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

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

  require "google/cloud/storage"

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

  renamed_file = file.copy new_name

  file.delete

  puts "#{file_name} has been renamed to #{renamed_file.name}"
end

REST API

JSON API

복사를 통해 객체를 이동하거나 이름을 바꾸는 방법에 대한 JSON API 안내는 객체 복사를 참조하세요.

XML API

복사를 통해 객체를 이동하거나 이름을 바꾸는 방법에 대한 XML API 안내는 객체 복사를 참조하세요.

원자적으로 객체 이름 바꾸기

이 섹션에서는 버킷 내에서 객체의 이름을 원자적으로 바꾸는 방법을 설명합니다. 객체의 이름을 바꾸려면 Cloud Storage JSON API의 Objects: move 메서드를 사용하면 됩니다.

REST API

JSON API

객체의 이름을 원자적으로 바꾸려면 다음을 실행하세요.

  1. Authorization 헤더에 대한 액세스 토큰을 생성하려면 gcloud CLI가 설치 및 초기화되어 있어야 합니다.

  2. cURL을 사용하여 Objects: move 요청으로 JSON API를 호출합니다.

    curl -X POST 
    -H "Authorization: Bearer $(gcloud auth print-access-token)"
    -H "Content-Length: 0"
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/SOURCE_OBJECT_NAME/moveTo/o/DESTINATION_OBJECT_NAME"

    각 항목의 의미는 다음과 같습니다.

    • BUCKET_NAME은 이름을 바꿀 객체가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • SOURCE_OBJECT_NAME은 이름을 바꿀 객체의 URL 인코딩 이름입니다. 예를 들어 pets/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.
    • DESTINATION_OBJECT_NAME은 사용할 URL로 인코딩된 이름입니다. 예를 들어 pets/cat.pngpets%2Fcat.png로 URL 인코딩됩니다.

다음 단계