列出值區

這個頁面說明如何列出專案中的 Cloud Storage 值區,值區將按照名稱依字母順序排列。

事前準備

如要取得列出 bucket 的權限,請要求管理員在包含要列出 bucket 的專案中,授予您「Storage 管理員」(roles/storage.admin) IAM 角色或「檢視者」(roles/viewer) 基本角色。

如要進一步瞭解如何授予專案角色,請參閱「管理專案存取權」。

這些角色具備 storage.buckets.list 權限,可列出 bucket。您也可以透過自訂角色取得這項權限。

列出專案中的值區

控制台

  1. 前往 Google Cloud 控制台的「Cloud Storage bucket」頁面。

    前往「Buckets」(值區) 頁面

清單會顯示所選專案中的 bucket。

您可以選擇使用篩選和排序功能,限制並整理清單中的結果。

指令列

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 在開發環境中執行 gcloud storage ls 指令:

    gcloud storage ls

    回應類似下列範例:

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

  3. 用戶端程式庫

    C++

    詳情請參閱「Cloud Storage C++ API 參考文件」。

    如要向 Cloud Storage 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

    下列範例會列出所有可用的值區。如果某個位置暫時無法使用,回應也會包含任何無法連線的 bucket 名稱。

    namespace gcs = ::google::cloud::storage;
    using ::google::cloud::StatusOr;
    [](gcs::Client client) {
      int count = 0;
      gcs::ListBucketsExtendedReader bucket_list = client.ListBucketsExtended();
      for (auto&& result : bucket_list) {
        if (!result) throw std::move(result).status();
    
        for (auto const& bucket_metadata : result->buckets) {
          std::cout << bucket_metadata.name() << "\n";
          ++count;
        }
        for (auto const& unreachable : result->unreachable) {
          std::cout << "Unreachable location: " << unreachable << "\n";
        }
      }
    
      if (count == 0) {
        std::cout << "No buckets in default project\n";
      }
    }

    下列範例會列出所有值區。如果某個位置暫時無法使用,服務會傳回錯誤。

    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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

    下列範例會列出所有可用的值區。如果某個位置暫時無法使用,回應也會包含任何無法連線的 bucket 名稱。

    
    using Google.Api.Gax;
    using Google.Apis.Storage.v1.Data;
    using Google.Cloud.Storage.V1;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public class ListBucketsWithPartialSuccessSample
    {
        /// <summary>
        /// Lists buckets, returning both the reachable buckets and the resource names of buckets from unreachable locations when specific regions are unreachable.
        /// </summary>
        /// <param name="projectId">The ID of the project to list the buckets.</param>
        public (IReadOnlyList<Bucket> Reachable, IReadOnlyList<string> Unreachable) ListBucketsWithPartialSuccess
            (string projectId = "your-project-id")
        {
            var storage = StorageClient.Create();
            var pagedResult = storage.ListBuckets(projectId, options: new ListBucketsOptions
            {
                ReturnPartialSuccess = true
            });
    
            var reachableBuckets = new List<Bucket>();
            var unreachableBuckets = new List<string>();
    
            foreach (var page in pagedResult.AsRawResponses())
            {
                reachableBuckets.AddRange(page.Items ?? Enumerable.Empty<Bucket>());
                unreachableBuckets.AddRange(page.Unreachable ?? Enumerable.Empty<string>());
            }
    
            Console.WriteLine("Buckets:");
            foreach (var bucket in reachableBuckets)
            {
                Console.WriteLine(bucket.Name);
            }
    
            if (unreachableBuckets.Any())
            {
                Console.WriteLine("The Resource Names of Buckets from Unreachable Locations:");
                foreach (var bucket in unreachableBuckets)
                {
                    Console.WriteLine(bucket);
                }
            }
            return (reachableBuckets, unreachableBuckets);
        }
    }

    下列範例會列出所有值區。如果某個位置暫時無法使用,服務會傳回錯誤。

    
    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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

    下列範例會列出所有可用的值區。如果某個位置暫時無法使用,回應也會包含任何無法連線的 bucket 名稱。

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"
    
    	"cloud.google.com/go/storage"
    	"google.golang.org/api/iterator"
    )
    
    // listBucketsPartialSuccess lists buckets in the project. If ReturnPartialSuccess
    // is true, the iterator will return reachable buckets and a list of
    // unreachable bucket resource names.
    func listBucketsPartialSuccess(w io.Writer, projectID string) error {
    	// projectID := "my-project-id"
    	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*30)
    	defer cancel()
    
    	it := client.Buckets(ctx, projectID)
    	// Enable returning unreachable buckets.
    	it.ReturnPartialSuccess = true
    
    	fmt.Fprintln(w, "Reachable buckets:")
    	for {
    		battrs, err := it.Next()
    		if err == iterator.Done {
    			break
    		}
    		if err != nil {
    			// Errors here usually indicate a problem with the overall list operation
    			// or connection, such as a network issue, rather than individual
    			// buckets being unreachable. Unreachable buckets due to issues like
    			// regional outages or permission issues are typically reported via the
    			// Unreachable() method below.
    			return err
    		}
    		fmt.Fprintf(w, "- %v\n", battrs.Name)
    	}
    
    	// Retrieve the list of buckets that were unreachable.
    	unreachable := it.Unreachable()
    	if len(unreachable) > 0 {
    		fmt.Fprintln(w, "\nUnreachable buckets:")
    		for _, r := range unreachable {
    			fmt.Fprintf(w, "- %v\n", r)
    		}
    	} else {
    		fmt.Fprintln(w, "\nNo unreachable buckets.")
    	}
    
    	return nil
    }
    

    下列範例會列出所有值區。如果某個位置暫時無法使用,服務會傳回錯誤。

    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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

    下列範例會列出所有可用的值區。如果某個位置暫時無法使用,回應也會包含任何無法連線的 bucket 名稱。

    
    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 ListBucketsWithPartialSuccess {
      public static void listBucketsWithPartialSuccess(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(Storage.BucketListOption.returnPartialSuccess(true));
    
        // Retrieve the list of buckets that are unreachable due to issues like regional outages or
        // permission issues
        System.out.println("Unreachable buckets: \n");
        for (Bucket bucket : buckets.iterateAll()) {
          if (Boolean.TRUE.equals(bucket.isUnreachable())) {
            System.out.println(bucket.getName());
          }
        }
      }
    }

    下列範例會列出所有值區。如果某個位置暫時無法使用,服務會傳回錯誤。

    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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

    下列範例會列出所有可用的值區。如果某個位置暫時無法使用,回應也會包含任何無法連線的 bucket 名稱。

    // Imports the Google Cloud client library
    const {Storage} = require('@google-cloud/storage');
    
    // Creates a client
    const storage = new Storage();
    
    async function listBucketsPartialSuccess() {
      const option = {
        returnPartialSuccess: true,
        maxResults: 5,
      };
      const [buckets, nextQuery, apiResponse] = await storage.getBuckets(option);
    
      if (nextQuery && nextQuery.pageToken) {
        console.log(`Next Page Token: ${nextQuery.pageToken}`);
      }
    
      console.log('\nBuckets:');
      buckets.forEach(bucket => {
        if (bucket.unreachable) {
          console.log(`${bucket.name} (unreachable: ${bucket.unreachable})`);
        } else {
          console.log(`${bucket.name}`);
        }
      });
    
      if (apiResponse.unreachable && apiResponse.unreachable.length > 0) {
        console.log('\nUnreachable Buckets:');
        apiResponse.unreachable.forEach(item => {
          console.log(item);
        });
      }
    }
    
    listBucketsPartialSuccess().catch(console.error);

    下列範例會列出所有值區。如果某個位置暫時無法使用,服務會傳回錯誤。

    // 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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

    下列範例會列出所有可用的值區。如果某個位置暫時無法使用,回應也會包含任何無法連線的 bucket 名稱。

    use Google\Cloud\Storage\StorageClient;
    
    /**
     * Retrieves a list of buckets while gracefully handling regional downtime.
     */
    function list_buckets_partial_success(): void
    {
        $storage = new StorageClient();
        $options = [ 'returnPartialSuccess' => true ];
        $buckets = $storage->buckets($options);
    
        // Check for unreachable locations first
        // Note: unreachable() returns an array of strings for buckets in unavailable regions
        if ($unreachable = $buckets->unreachable()) {
            foreach ($unreachable as $location) {
                printf('Unreachable Bucket: %s' . PHP_EOL, $location);
            }
        }
    
        // Iterate through the buckets that were successfully retrieved
        foreach ($buckets as $bucket) {
            printf('Bucket: %s' . PHP_EOL, $bucket->name());
        }
    }

    下列範例會列出所有值區。如果某個位置暫時無法使用,服務會傳回錯誤。

    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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

    下列範例會列出所有可用的值區。如果某個位置暫時無法使用,回應也會包含任何無法連線的 bucket 名稱。

    from google.cloud import storage
    
    
    def list_buckets_with_partial_success():
        """Lists buckets and includes unreachable buckets in the response."""
    
        storage_client = storage.Client()
    
        buckets_iterator = storage_client.list_buckets(return_partial_success=True)
    
        for page in buckets_iterator.pages:
            if page.unreachable:
                print("Unreachable locations in this page:")
                for location in page.unreachable:
                    print(location)
    
            print("Reachable buckets in this page:")
            for bucket in page:
                print(bucket.name)
    
    

    下列範例會列出所有值區。如果某個位置暫時無法使用,服務會傳回錯誤。

    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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

    下列範例會列出所有可用的值區。如果某個位置暫時無法使用,回應也會包含任何無法連線的 bucket 名稱。

    # Demonstrates listing Google Cloud Storage buckets with support for partial success.
    #
    # This method initializes a Google Cloud Storage client and requests a list of buckets.
    # When `return_partial_success` is true, the API will return available buckets
    # and a list of any buckets that were unreachable.
    #
    # @param return_partial_success_flag [Boolean] Whether to allow partial success from the API.
    #   - true: returns the available buckets and populates `unreachable` with bucket names if any.
    #   - false: throws an error if any buckets are unreachable.
    def list_buckets_with_partial_success return_partial_success_flag:
      require "google/cloud/storage"
    
      storage = Google::Cloud::Storage.new
      bucket_list = storage.buckets return_partial_success: return_partial_success_flag
    
      puts "Reachable buckets:"
      # limiting the bucket count to be printed to 10 for brevity
      bucket_list.take(10).each do |bucket|
        puts bucket.name
      end
    
      if bucket_list.unreachable
        puts "\nUnreachable buckets:"
        # limiting the bucket count to be printed to 10 for brevity
        bucket_list.unreachable.take(10).each do |unreachable_bucket_name|
          puts unreachable_bucket_name
        end
      end
    end

    下列範例會列出所有值區。如果某個位置暫時無法使用,服務會傳回錯誤。

    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. 安裝並初始化gcloud CLI,以便為 Authorization 標頭產生存取權杖。

    2. 使用 cURL 透過列出值區的要求呼叫 JSON API

      curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        "https://storage.googleapis.com/storage/v1/b?project=PROJECT_IDENTIFIER&returnPartialSuccess=RETURN_PARTIAL_SUCCESS_BOOLEAN"

      更改下列內容:

      • PROJECT_IDENTIFIER:包含您要列出值區的專案 ID 或編號。例如:my-project
      • RETURN_PARTIAL_SUCCESS_BOOLEAN:如果即使部分 bucket 無法存取 (因為位置暫時無法使用),您仍想傳回 bucket 清單,請將這個值設為 true。如果設為 false,只有在所有位置都能連線時,要求才會傳回 bucket 清單,否則會傳回錯誤。預設值為 false

    XML API

    1. 安裝並初始化gcloud CLI,以便為 Authorization 標頭產生存取權杖。

    2. 使用 cURL 透過 GET 服務要求呼叫 XML API

      curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "x-goog-project-id: PROJECT_ID" \
        "https://storage.googleapis.com"

      PROJECT_ID 替換為包含要列出值區的專案 ID。例如:my-project

後續步驟