버킷 나열

이 페이지에서는 이름이 사전 편찬 순서 대로 지정된 Cloud Storage 버킷을 프로젝트 목록에 나열하는 방법을 보여줍니다.

시작하기 전에

버킷을 나열하는 데 필요한 권한을 얻으려면 관리자에게 나열할 버킷이 포함된 프로젝트의 스토리지 관리자(roles/storage.admin) IAM 역할 또는 뷰어(roles/viewer) 기본 역할을 부여해 달라고 요청하세요.

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

이 역할에는 버킷을 나열하는 데 필요한 storage.buckets.list 권한이 포함됩니다. 커스텀 역할로 이 권한을 얻을 수도 있습니다.

프로젝트에서 버킷 나열

콘솔

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

    버킷으로 이동

현재 선택된 프로젝트의 일부인 버킷이 목록에 나타납니다.

필터링을 사용하여 목록의 결과 범위를 좁힙니다(선택사항).

명령줄

  1. Google Cloud 콘솔에서 Cloud Shell을 활성화합니다.

    Cloud Shell 활성화

    Google Cloud 콘솔 하단에서 Cloud Shell 세션이 시작되고 명령줄 프롬프트가 표시됩니다. Cloud Shell은 Google Cloud CLI가 사전 설치된 셸 환경으로, 현재 프로젝트의 값이 이미 설정되어 있습니다. 세션이 초기화되는 데 몇 초 정도 걸릴 수 있습니다.

  2. 개발 환경에서 gcloud storage ls 명령어를 실행합니다.

    gcloud storage ls

    응답은 다음 예시와 같습니다.

    gs://BUCKET_NAME1/
      gs://BUCKET_NAME2/
      gs://BUCKET_NAME3/
      ...

클라이언트 라이브러리

C++

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

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client) {
  int count = 0;
  gcs::ListBucketsReader bucket_list = client.ListBuckets();
  for (auto&& bucket_metadata : bucket_list) {
    if (!bucket_metadata) throw std::move(bucket_metadata).status();

    std::cout << bucket_metadata->name() << "\n";
    ++count;
  }

  if (count == 0) {
    std::cout << "No buckets in default project\n";
  }
}

C#

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

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


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class ListBucketsSample
{
    public IEnumerable<Bucket> ListBuckets(string projectId = "your-project-id")
    {
        var storage = StorageClient.Create();
        var buckets = storage.ListBuckets(projectId);
        Console.WriteLine("Buckets:");
        foreach (var bucket in buckets)
        {
            Console.WriteLine(bucket.Name);
        }
        return buckets;
    }
}

Go

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

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

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

	"cloud.google.com/go/storage"
	"google.golang.org/api/iterator"
)

// listBuckets lists buckets in the project.
func listBuckets(w io.Writer, projectID string) ([]string, error) {
	// projectID := "my-project-id"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

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

	var buckets []string
	it := client.Buckets(ctx, projectID)
	for {
		battrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, err
		}
		buckets = append(buckets, battrs.Name)
		fmt.Fprintf(w, "Bucket: %v\n", battrs.Name)
	}
	return buckets, nil
}

Java

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

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

import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListBuckets {
  public static void listBuckets(String projectId) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Page<Bucket> buckets = storage.list();

    for (Bucket bucket : buckets.iterateAll()) {
      System.out.println(bucket.getName());
    }
  }
}

Node.js

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

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

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

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

async function listBuckets() {
  const [buckets] = await storage.getBuckets();

  console.log('Buckets:');
  buckets.forEach(bucket => {
    console.log(bucket.name);
  });
}

listBuckets().catch(console.error);

PHP

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

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

use Google\Cloud\Storage\StorageClient;

/**
 * List all Cloud Storage buckets for the current project.
 */
function list_buckets(): void
{
    $storage = new StorageClient();
    foreach ($storage->buckets() as $bucket) {
        printf('Bucket: %s' . PHP_EOL, $bucket->name());
    }
}

Python

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

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

from google.cloud import storage

def list_buckets():
    """Lists all buckets."""

    storage_client = storage.Client()
    buckets = storage_client.list_buckets()

    for bucket in buckets:
        print(bucket.name)

Ruby

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

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

def list_buckets
  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new

  storage.buckets.each do |bucket|
    puts bucket.name
  end
end

REST API

JSON API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 GET 서비스 요청으로 JSON API를 호출합니다.

    curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage./storage/v1/b?project=PROJECT_IDENTIFIER"

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

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
    • PROJECT_IDENTIFIER는 나열할 버킷이 포함된 프로젝트의 ID 또는 번호입니다. 예를 들면 my-project입니다.

XML API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 GET 서비스 요청으로 XML API를 호출합니다.

    curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "x-goog-project-id: PROJECT_ID" \
      "https://storage."

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

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
    • PROJECT_ID는 나열할 버킷이 포함된 프로젝트의 ID입니다. 예를 들면 my-project입니다.

다음 단계