폴더 이름 바꾸기

이 페이지에서는 계층적 네임스페이스가 사용 설정된 버킷에서 폴더 이름을 바꾸는 방법을 설명합니다.

이름 바꾸기 작업은 폴더, 하위 폴더, 객체 및 관리 폴더를 포함한 관련 리소스의 이름을 단일 원자 작업으로 재귀적으로 바꿉니다.

이름 바꾸기 작업은 원자적입니다. 이 작업은 성공적으로 완료되고 리소스를 새 경로로 이동하거나 오류가 발생하여 실패합니다. 오류가 발생하면 모든 리소스가 원래 상태로 복원됩니다.

계층적 네임스페이스가 사용 설정된 버킷에서 폴더 이름 바꾸기는 메타데이터 전용 작업입니다. 폴더 내에서 객체를 물리적으로 이동하거나 복사하지 않으므로 객체 복사 비용이 발생하지 않습니다.

하지만 계층적 네임스페이스가 사용 설정되지 않은 버킷에서는 폴더가 시뮬레이션됩니다. 시뮬레이션된 폴더 이름을 바꾸거나 이동하려면 폴더 내의 각 객체를 복사하고 삭제해야 합니다. 폴더에 많은 객체가 포함되어 있는 경우 이름 바꾸기 프로세스가 비효율적이고 비용이 많이 들 수 있습니다. 시뮬레이션된 폴더의 이름 변경 또는 이동도 원자적이지 않습니다. 즉, 프로세스가 실패할 경우 일부 객체만 이동된 일관되지 않은 상태로 남아 있을 수 있습니다.

폴더 이름 변경 프로세스 중에 이름을 바꿀 리소스를 읽고 나열할 수 있습니다. 그러나 영향을 받는 리소스에서는 쓰기 작업을 실행할 수 없습니다.

폴더 이름 바꾸기 작업은 버킷에서 장기 실행 작업을 시작합니다.

필요한 역할

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

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

필요한 정확한 권한을 보려면 필수 권한 섹션을 펼치세요.

필수 권한

  • storage.folders.rename
    • 이 권한은 소스 폴더에 필요합니다.
  • storage.folders.create
    • 대상 폴더에 이 권한이 필요합니다.

다른 커스텀 역할이나 사전 정의된 역할을 사용하여 위의 권한을 얻을 수도 있습니다. 폴더 이름 변경 외에도 폴더를 관리할 수 있는 더 많은 권한이 있는 역할이 필요한 경우 관리자에게 다음 역할 중 하나를 부여해 달라고 요청하세요.

  • 스토리지 폴더 관리자(roles/storage.folderAdmin)
  • 스토리지 객체 관리자(roles/storage.objectAdmin)
  • 스토리지 관리자(roles/storage.admin)

어떤 역할이 어떤 권한과 연결되어 있는지 확인하려면 Cloud Storage에 대한 IAM 역할을 참조하세요.

폴더 이름 바꾸기

클라이언트 라이브러리

C++

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

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name, std::string const& source_folder_id,
   std::string const& dest_folder_id) {
  auto name = std::string{"projects/_/buckets/"} + bucket_name + "/folders/" +
              source_folder_id;
  // Start a rename operation and block until it completes. Real applications
  // may want to setup a callback, wait on a coroutine, or poll until it
  // completes.
  auto renamed = client.RenameFolder(name, dest_folder_id).get();
  if (!renamed) throw std::move(renamed).status();

  std::cout << "Renamed: " << source_folder_id << " to: " << dest_folder_id
            << "\n";
}

Go

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

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

	control "cloud.google.com/go/storage/control/apiv2"
	"cloud.google.com/go/storage/control/apiv2/controlpb"
)

// renameFolder changes the name of an existing folder.
func renameFolder(w io.Writer, bucket, src, dst string) error {
	// bucket := "bucket-name"
	// src := "original-folder-name"
	// dst := "new-folder-name"

	ctx := context.Background()
	client, err := control.NewStorageControlClient(ctx)
	if err != nil {
		return fmt.Errorf("NewStorageControlClient: %w", err)
	}
	defer client.Close()

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

	// Construct source folder path including the bucket name.
	srcPath := fmt.Sprintf("projects/_/buckets/%v/folders/%v", bucket, src)

	req := &controlpb.RenameFolderRequest{
		Name:                srcPath,
		DestinationFolderId: dst,
	}
	op, err := client.RenameFolder(ctx, req)
	if err != nil {
		return fmt.Errorf("RenameFolder(%q): %w", srcPath, err)
	}

	// Wait for long-running operation to complete.
	f, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("waiting for RenameFolder: %w", err)
	}

	fmt.Fprintf(w, "folder %v moved to new path %v", srcPath, f.Name)
	return nil
}

Java

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

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.storage.control.v2.Folder;
import com.google.storage.control.v2.FolderName;
import com.google.storage.control.v2.RenameFolderMetadata;
import com.google.storage.control.v2.RenameFolderRequest;
import com.google.storage.control.v2.StorageControlClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public final class RenameFolder {

  public static void renameFolder(
      String bucketName, String sourceFolderName, String destinationFolderName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // The name of the bucket
    // String bucketName = "your-unique-bucket-name";

    // The name of the folder within the bucket
    // String sourceFolderName = "your-unique-source-folder-name";

    // The new name of the folder within the bucket
    // String destinationFolderName = "your-unique-destination-folder-name";

    try (StorageControlClient storageControl = StorageControlClient.create()) {

      // Set project to "_" to signify globally scoped bucket
      String sourceFolderResourceName = FolderName.format("_", bucketName, sourceFolderName);
      RenameFolderRequest request =
          RenameFolderRequest.newBuilder()
              .setName(sourceFolderResourceName)
              .setDestinationFolderId(destinationFolderName)
              .build();

      OperationFuture<Folder, RenameFolderMetadata> renameOperation =
          storageControl.renameFolderAsync(request);

      Folder destinationFolder = renameOperation.get(30, TimeUnit.SECONDS);

      System.out.printf(
          "Renamed folder from %s to %s%n", sourceFolderResourceName, destinationFolder.getName());
    }
  }
}

Node.js

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

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */

// The name of your GCS bucket
// const bucketName = 'bucketName';

// The source folder name
// const sourceFolderName = 'currentFolderName';

// The destination folder ID
// const destinationFolderName = 'destinationFolderName';

// Imports the Control library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

// Instantiates a client
const controlClient = new StorageControlClient();

async function callRenameFolder() {
  const folderPath = `projects/_/buckets/${bucketName}/folders/${sourceFolderName}`;

  // Create the request
  const request = {
    name: folderPath,
    destinationFolderId: destinationFolderName,
  };

  // Run request
  const response = await controlClient.renameFolder(request);
  console.log(
    `Renamed folder ${sourceFolderName} to ${destinationFolderName}.`
  );
}

callRenameFolder();

PHP

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

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
use Google\Cloud\Storage\Control\V2\RenameFolderRequest;

/**
 * Rename a folder in an existing bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $sourceFolder The source folder ID.
 *        (e.g. 'my-folder')
 * @param string $destinationFolder The destination folder ID.
 *        (e.g. 'my-folder')
 */
function rename_folder(string $bucketName, string $sourceFolder, string $destinationFolder): void
{
    $storageControlClient = new StorageControlClient();

    // Set project to "_" to signify global bucket
    $formattedName = $storageControlClient->folderName('_', $bucketName, $sourceFolder);

    $request = new RenameFolderRequest([
        'name' => $formattedName,
        'destination_folder_id' => $destinationFolder,
    ]);

    $storageControlClient->renameFolder($request);

    printf('Renamed folder %s to %s', $sourceFolder, $destinationFolder);
}

Python

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

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import storage_control_v2


def rename_folder(
    bucket_name: str, source_folder_name: str, destination_folder_name: str
) -> None:
    # The ID of your GCS bucket
    # bucket_name = "your-unique-bucket-name"
    #
    # The source folder ID
    # source_folder_name = "current-folder-name"
    #
    # The destination folder ID
    # destination_folder_name = "new-folder-name"

    storage_control_client = storage_control_v2.StorageControlClient()
    # The storage bucket path uses the global access pattern, in which the "_"
    # denotes this bucket exists in the global namespace.
    source_folder_path = storage_control_client.folder_path(
        project="_", bucket=bucket_name, folder=source_folder_name
    )

    request = storage_control_v2.RenameFolderRequest(
        name=source_folder_path,
        destination_folder_id=destination_folder_name,
    )

    operation = storage_control_client.rename_folder(request=request)
    operation.result(60)

    print(f"Renamed folder {source_folder_name} to {destination_folder_name}")

Ruby

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

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def rename_folder bucket_name:, source_folder_id:, destination_folder_id:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"
  #
  # The source folder ID
  # source_folder_id = "current-folder-id"
  #
  # The destination folder ID, e.g. foo/bar/
  # destination_folder_id = "destination-folder-id"

  require "google/cloud/storage/control"

  storage_control = Google::Cloud::Storage::Control.storage_control

  # The storage folder path uses the global access pattern, in which the "_"
  # denotes this bucket exists in the global namespace.
  folder_path = storage_control.folder_path project: "_", bucket: bucket_name, folder: source_folder_id

  request = Google::Cloud::Storage::Control::V2::RenameFolderRequest.new name: folder_path,
                                                                         destination_folder_id: destination_folder_id

  storage_control.rename_folder request

  puts "Renamed folder #{source_folder_id} to #{destination_folder_id}"
end

REST API

JSON API

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

    또는 OAuth 2.0 Playground를 사용하여 액세스 토큰을 만들고 Authorization 헤더에 포함할 수 있습니다.

  2. cURL을 사용하여 폴더 이름 변경 요청으로 JSON API를 호출합니다.

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/folders/SOURCE_PATH/renameTo/folders/DESTINATION_PATH"

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

    • BUCKET_NAME는 이름을 바꿀 폴더가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • SOURCE_PATH는 소스 폴더의 URL 인코딩 경로입니다. 예를 들어 my-src-folder/my-src-folder%2F로 URL 인코딩됩니다.
    • DESTINATION_PATH는 대상 폴더의 URL 인코딩 경로입니다. 예를 들어 my-dest-folder/my-dest-folder%2F로 URL 인코딩됩니다.

다음 단계

직접 사용해 보기

Google Cloud를 처음 사용하는 경우 계정을 만들어 실제 시나리오에서 Cloud Storage의 성능을 평가할 수 있습니다. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.

Cloud Storage 무료로 사용해 보기