Use HeadBucket com um AWS SDK ou CLI - AWS Exemplos de código do SDK

Há mais exemplos de AWS SDK disponíveis no repositório AWS Doc SDK Examples GitHub .

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use HeadBucket com um AWS SDK ou CLI

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

Bash
AWS CLI com script Bash
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

############################################################################### # function bucket_exists # # This function checks to see if the specified bucket already exists. # # Parameters: # $1 - The name of the bucket to check. # # Returns: # 0 - If the bucket already exists. # 1 - If the bucket doesn't exist. ############################################################################### function bucket_exists() { local bucket_name bucket_name=$1 # Check whether the bucket already exists. # We suppress all output - we're interested only in the return code. if aws s3api head-bucket \ --bucket "$bucket_name" \ >/dev/null 2>&1; then return 0 # 0 in Bash script means true. else return 1 # 1 in Bash script means false. fi }
  • Para obter detalhes da API, consulte HeadBucketem Referência de AWS CLI Comandos.

CLI
AWS CLI

O seguinte comando verifica o acesso ao bucket amzn-s3-demo-bucket:

aws s3api head-bucket --bucket amzn-s3-demo-bucket

Se o bucket existir e você tiver acesso a ele, nenhuma saída será retornada. Caso contrário, uma mensagem de erro será exibida. Por exemplo:

A client error (404) occurred when calling the HeadBucket operation: Not Found
  • Para obter detalhes da API, consulte HeadBucketem Referência de AWS CLI Comandos.

Go
SDK para Go V2
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

import ( "bytes" "context" "errors" "fmt" "io" "log" "os" "time" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/feature/s3/manager" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go-v2/service/s3/types" "github.com/aws/smithy-go" ) // 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 } // BucketExists checks whether a bucket exists in the current account. func (basics BucketBasics) BucketExists(ctx context.Context, bucketName string) (bool, error) { _, err := basics.S3Client.HeadBucket(ctx, &s3.HeadBucketInput{ Bucket: aws.String(bucketName), }) exists := true if err != nil { var apiError smithy.APIError if errors.As(err, &apiError) { switch apiError.(type) { case *types.NotFound: log.Printf("Bucket %v is available.\n", bucketName) exists = false err = nil default: log.Printf("Either you don't have access to bucket %v or another error occurred. "+ "Here's what happened: %v\n", bucketName, err) } } } else { log.Printf("Bucket %v exists and you already own it.", bucketName) } return exists, err }
  • Para obter detalhes da API, consulte HeadBucketa Referência AWS SDK para Go da API.

PowerShell
Ferramentas para PowerShell V5

Exemplo 1: Esse comando retorna a saída com o código de status HTTP 200 OK para o bucket existente quando o usuário tem permissão para acessá-lo. BucketArn o parâmetro só é compatível com buckets de diretório do S3.

Get-S3HeadBucket -BucketName amzn-s3-demo-bucket

Saída:

AccessPointAlias : False BucketArn : BucketLocationName : BucketLocationType : BucketRegion : us-east-2 ResponseMetadata : Amazon.Runtime.ResponseMetadata ContentLength : 0 HttpStatusCode : OK

Exemplo 2: Esse comando gera um erro com o código de status HTTP NotFound para um bucket inexistente.

Get-S3HeadBucket -BucketName amzn-s3-non-existing-bucket

Saída:

Get-S3HeadBucket: Error making request with Error Code NotFound and Http Status Code NotFound. No further error information was returned by the service.

Exemplo 3: Esse comando gera um erro com o código de status HTTP Proibido para um bucket existente em que o usuário não tem permissão para acessá-lo.

Get-S3HeadBucket -BucketName amzn-s3-no-access-bucket

Saída:

Get-S3HeadBucket: Error making request with Error Code Forbidden and Http Status Code Forbidden. No further error information was returned by the service.
  • Para obter detalhes da API, consulte HeadBucketem Referência de Ferramentas da AWS para PowerShell cmdlet (V5).

Python
SDK para Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

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 def exists(self): """ Determine whether the bucket exists and you have access to it. :return: True when the bucket exists; otherwise, False. """ try: self.bucket.meta.client.head_bucket(Bucket=self.bucket.name) logger.info("Bucket %s exists.", self.bucket.name) exists = True except ClientError: logger.warning( "Bucket %s doesn't exist or you don't have access to it.", self.bucket.name, ) exists = False return exists
  • Para obter detalhes da API, consulte a HeadBucketReferência da API AWS SDK for Python (Boto3).