ListBuckets 搭配 AWS SDK或 使用 CLI - AWS SDK 程式碼範例

文件範例儲存庫中有更多 AWS SDK可用的範例。 AWS SDK GitHub

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

ListBuckets 搭配 AWS SDK或 使用 CLI

下列程式碼範例示範如何使用 ListBuckets

.NET
AWS SDK for .NET
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

namespace ListBucketsExample { using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; /// <summary> /// This example uses the AWS SDK for .NET to list the Amazon Simple Storage /// Service (Amazon S3) buckets belonging to the default account. /// </summary> public class ListBuckets { private static IAmazonS3 _s3Client; /// <summary> /// Get a list of the buckets owned by the default user. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <returns>The response from the ListingBuckets call that contains a /// list of the buckets owned by the default user.</returns> public static async Task<ListBucketsResponse> GetBuckets(IAmazonS3 client) { return await client.ListBucketsAsync(); } /// <summary> /// This method lists the name and creation date for the buckets in /// the passed List of S3 buckets. /// </summary> /// <param name="bucketList">A List of S3 bucket objects.</param> public static void DisplayBucketList(List<S3Bucket> bucketList) { bucketList .ForEach(b => Console.WriteLine($"Bucket name: {b.BucketName}, created on: {b.CreationDate}")); } public static async Task Main() { // The client uses the AWS Region of the default user. // If the Region where the buckets were created is different, // pass the Region to the client constructor. For example: // _s3Client = new AmazonS3Client(RegionEndpoint.USEast1); _s3Client = new AmazonS3Client(); var response = await GetBuckets(_s3Client); DisplayBucketList(response.Buckets); } } }
  • 如需API詳細資訊,請參閱 參考 ListBuckets中的 。 AWS SDK for .NET API

C++
SDK 適用於 C++
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

bool AwsDoc::S3::listBuckets(const Aws::S3::S3ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); auto outcome = client.ListBuckets(); bool result = true; if (!outcome.IsSuccess()) { std::cerr << "Failed with error: " << outcome.GetError() << std::endl; result = false; } else { std::cout << "Found " << outcome.GetResult().GetBuckets().size() << " buckets\n"; for (auto &&b: outcome.GetResult().GetBuckets()) { std::cout << b.GetName() << std::endl; } } return result; }
  • 如需API詳細資訊,請參閱 參考 ListBuckets中的 。 AWS SDK for C++ API

CLI
AWS CLI

下列命令使用 list-buckets命令來顯示所有 Amazon S3 儲存貯體的名稱 (跨所有區域):

aws s3api list-buckets --query "Buckets[].Name"

查詢選項會將 的輸出list-buckets向下篩選為僅儲存貯體名稱。

如需儲存貯體的詳細資訊,請參閱 Amazon S3 開發人員指南 中的使用 Amazon S3 儲存貯體。

  • 如需API詳細資訊,請參閱 命令參考 ListBuckets中的 。 AWS CLI

Go
SDK for Go V2
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

// BucketBasics encapsulates the Amazon Simple Storage Service (Amazon S3) actions // used in the examples. // It contains S3Client, an Amazon S3 service client that is used to perform bucket // and object actions. type BucketBasics struct { S3Client *s3.Client } // ListBuckets lists the buckets in the current account. func (basics BucketBasics) ListBuckets() ([]types.Bucket, error) { result, err := basics.S3Client.ListBuckets(context.TODO(), &s3.ListBucketsInput{}) var buckets []types.Bucket if err != nil { log.Printf("Couldn't list buckets for your account. Here's why: %v\n", err) } else { buckets = result.Buckets } return buckets, err }
  • 如需API詳細資訊,請參閱 參考 ListBuckets中的 。 AWS SDK for Go API

Java
SDK 適用於 Java 2.x
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.Bucket; import software.amazon.awssdk.services.s3.model.ListBucketsResponse; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListBuckets { public static void main(String[] args) { Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); listAllBuckets(s3); } public static void listAllBuckets(S3Client s3) { ListBucketsResponse response = s3.listBuckets(); List<Bucket> bucketList = response.buckets(); for (Bucket bucket: bucketList) { System.out.println("Bucket name "+bucket.name()); } } }
  • 如需API詳細資訊,請參閱 參考 ListBuckets中的 。 AWS SDK for Java 2.x API

JavaScript
SDK 適用於 JavaScript (v3)
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

列出儲存貯體。

import { ListBucketsCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new ListBucketsCommand({}); try { const { Owner, Buckets } = await client.send(command); console.log( `${Owner.DisplayName} owns ${Buckets.length} bucket${ Buckets.length === 1 ? "" : "s" }:`, ); console.log(`${Buckets.map((b) => ` • ${b.Name}`).join("\n")}`); } catch (err) { console.error(err); } };
PowerShell
適用於 的工具 PowerShell

範例 1:此命令會傳回所有 S3 儲存貯體。

Get-S3Bucket

範例 2:此命令會傳回名為 "test-files" 的儲存貯體

Get-S3Bucket -BucketName amzn-s3-demo-bucket
  • 如需API詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考 ListBuckets中的 。

Python
SDK for Python (Boto3)
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class BucketWrapper: """Encapsulates S3 bucket actions.""" def __init__(self, bucket): """ :param bucket: A Boto3 Bucket resource. This is a high-level resource in Boto3 that wraps bucket actions in a class-like structure. """ self.bucket = bucket self.name = bucket.name @staticmethod def list(s3_resource): """ Get the buckets in all Regions for the current account. :param s3_resource: A Boto3 S3 resource. This is a high-level resource in Boto3 that contains collections and factory methods to create other high-level S3 sub-resources. :return: The list of buckets. """ try: buckets = list(s3_resource.buckets.all()) logger.info("Got buckets: %s.", buckets) except ClientError: logger.exception("Couldn't get buckets.") raise else: return buckets
  • 如需API詳細資訊,請參閱 ListBuckets 中的 AWS SDK for Python (Boto3) API參考

Ruby
SDK 適用於 Ruby
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

require 'aws-sdk-s3' # Wraps Amazon S3 resource actions. class BucketListWrapper attr_reader :s3_resource # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource. def initialize(s3_resource) @s3_resource = s3_resource end # Lists buckets for the current account. # # @param count [Integer] The maximum number of buckets to list. def list_buckets(count) puts 'Found these buckets:' @s3_resource.buckets.each do |bucket| puts "\t#{bucket.name}" count -= 1 break if count.zero? end true rescue Aws::Errors::ServiceError => e puts "Couldn't list buckets. Here's why: #{e.message}" false end end # Example usage: def run_demo wrapper = BucketListWrapper.new(Aws::S3::Resource.new) wrapper.list_buckets(25) end run_demo if $PROGRAM_NAME == __FILE__
  • 如需API詳細資訊,請參閱 參考 ListBuckets中的 。 AWS SDK for Ruby API

Rust
SDK for Rust
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

async fn show_buckets( strict: bool, client: &Client, region: BucketLocationConstraint, ) -> Result<(), S3ExampleError> { let mut buckets = client.list_buckets().into_paginator().send(); let mut num_buckets = 0; let mut in_region = 0; while let Some(Ok(output)) = buckets.next().await { for bucket in output.buckets() { num_buckets += 1; if strict { let r = client .get_bucket_location() .bucket(bucket.name().unwrap_or_default()) .send() .await?; if r.location_constraint() == Some(&region) { println!("{}", bucket.name().unwrap_or_default()); in_region += 1; } } else { println!("{}", bucket.name().unwrap_or_default()); } } } println!(); if strict { println!( "Found {} buckets in the {} region out of a total of {} buckets.", in_region, region, num_buckets ); } else { println!("Found {} buckets in all regions.", num_buckets); } Ok(()) }
  • 如需API詳細資訊,請參閱 ListBuckets 中的 AWS SDK for Rust API參考

Swift
SDK 適用於 Swift
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

import AWSS3 /// Return an array containing information about every available bucket. /// /// - Returns: An array of ``S3ClientTypes.Bucket`` objects describing /// each bucket. public func getAllBuckets() async throws -> [S3ClientTypes.Bucket] { return try await client.listBuckets(input: ListBucketsInput()) }
  • 如需API詳細資訊,請參閱 ListBuckets 中的 AWS SDK Swift API參考