Usar ListBuckets com um SDK da AWS ou uma ferramenta de linha de comandos - Amazon Simple Storage Service

Usar ListBuckets com um SDK da AWS ou uma ferramenta de linha de comandos

Os exemplos de código a seguir mostram como usar o ListBuckets.

.NET
AWS SDK for .NET
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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); } } }
  • Para obter detalhes da API, consulte ListBuckets na Referência da API AWS SDK for .NET.

C++
SDK para C++
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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; }
  • Para obter detalhes da API, consulte ListBuckets na Referência da API AWS SDK for C++.

CLI
AWS CLI

O seguinte comando usa o comando list-buckets para exibir os nomes de todos os buckets do Amazon S3 (em todas as regiões):

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

A opção de consulta filtra a saída de list-buckets até sobrar apenas os nomes dos buckets.

Para obter mais informações sobre buckets, consulte Working with Amazon S3 Buckets no Guia do desenvolvedor do Amazon S3.

  • Para obter detalhes da API, consulte ListBuckets na Referência de comandos da AWS CLI.

Go
SDK para Go V2
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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 }
  • Para obter detalhes da API, consulte ListBuckets na Referência da API AWS SDK for Go.

Java
SDK para Java 2.x
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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()); } } }
  • Para obter informações da API, consulte ListBuckets na Referência da API AWS SDK for Java 2.x.

JavaScript
SDK para JavaScript (v3)
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

Liste os buckets.

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
Tools for PowerShell

Exemplo 1: este comando retorna todos os buckets do S3.

Get-S3Bucket

Exemplo 2: este comando retorna um bucket denominado “test-files”.

Get-S3Bucket -BucketName test-files
  • Para obter informações da API, consulte ListBuckets na AWS Tools for PowerShell Cmdlet Reference.

Python
SDK para Python (Boto3).
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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
  • Para obter detalhes da API, consulte ListBuckets na Referência da API AWS SDK para Python (Boto3).

Ruby
SDK para Ruby
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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__
  • Para obter detalhes da API, consulte ListBuckets na Referência da API AWS SDK for Ruby.

Rust
SDK para Rust
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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(()) }
  • Para obter detalhes da API, consulte ListBuckets na Referência da API AWS SDK para Rust.

Swift
SDK para Swift
nota

Esta é a documentação de pré-lançamento de um SDK na versão de visualização. Está sujeita a alteração.

nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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 }
  • Para obter detalhes da API, consulte ListBuckets na Referência de API do AWS SDK para Swift.

Para ver uma lista completa dos Guias do desenvolvedor de SDK da AWS e exemplos de código, consulte Usar este serviço com um AWS SDK. Este tópico também inclui informações sobre como começar e detalhes sobre versões anteriores do SDK.