Elenca i bucket Amazon S3 utilizzando un SDK AWS - Amazon Simple Storage Service

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Elenca i bucket Amazon S3 utilizzando un SDK AWS

Gli esempi di codice seguenti mostrano come elencare i bucket S3.

.NET
AWS SDK for .NET
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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); } } }
  • Per i dettagli sull'API, ListBucketsconsulta AWS SDK for .NET API Reference.

C++
SDK per C++
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

bool AwsDoc::S3::ListBuckets(const Aws::Client::ClientConfiguration &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; }
  • Per i dettagli sull'API, ListBucketsconsulta AWS SDK for C++ API Reference.

CLI
AWS CLI

Il comando seguente utilizza il list-buckets comando per visualizzare i nomi di tutti i bucket Amazon S3 (in tutte le regioni):

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

L'opzione query filtra l'output dei list-buckets soli nomi dei bucket.

Per ulteriori informazioni sui bucket, consulta Working with Amazon S3 Buckets nella Amazon S3 Developer Guide.

  • Per i dettagli sull'API, consulta ListBucketsCommand Reference.AWS CLI

Go
SDK per Go V2
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 }
  • Per i dettagli sull'API, ListBucketsconsulta AWS SDK for Go API Reference.

Java
SDK per Java 2.x
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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()); } } }
  • Per i dettagli sull'API, ListBucketsconsulta AWS SDK for Java 2.x API Reference.

JavaScript
SDK per JavaScript (v3)
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Elenca i bucket.

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); } };
Python
SDK per Python (Boto3)
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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
  • Per i dettagli sull'API, consulta ListBuckets AWSSDK for Python (Boto3) API Reference.

Ruby
SDK per Ruby
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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__
  • Per i dettagli sull'API, ListBucketsconsulta AWS SDK for Ruby API Reference.

Rust
SDK per Rust
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

async fn show_buckets(strict: bool, client: &Client, region: &str) -> Result<(), Error> { let resp = client.list_buckets().send().await?; let buckets = resp.buckets(); let num_buckets = buckets.len(); let mut in_region = 0; for bucket in buckets { if strict { let r = client .get_bucket_location() .bucket(bucket.name().unwrap_or_default()) .send() .await?; if r.location_constraint().unwrap().as_ref() == 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(()) }
  • Per i dettagli sulle API, consulta la ListBucketsguida di riferimento all'API AWS SDK for Rust.

Swift
SDK per Swift
Nota

Si tratta di una documentazione di pre-rilascio di un SDK nella versione di anteprima. ed è soggetta a modifiche.

Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// 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] { let output = try await client.listBuckets(input: ListBucketsInput()) guard let buckets = output.buckets else { return [] } return buckets }
  • Per i dettagli sull'API, consulta la ListBucketsguida di riferimento all'API AWS SDK for Swift.

Per un elenco completo delle guide per sviluppatori AWS SDK e degli esempi di codice, consulta. Utilizzo del servizio con un SDK AWS Questo argomento include anche informazioni su come iniziare e dettagli sulle versioni precedenti dell'SDK.