将 HeadBucket 与 AWS SDK 或 CLI 配合使用 - AWS SDK 代码示例

AWS 文档 SDK 示例 GitHub 存储库中还有更多 AWS SDK 示例。

HeadBucket 与 AWS SDK 或 CLI 配合使用

以下代码示例演示如何使用 HeadBucket

Bash
AWS CLI 及 Bash 脚本
注意

查看 GitHub,了解更多信息。查找完整示例,了解如何在 AWS 代码示例存储库中进行设置和运行。

############################################################################### # 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 }
  • 有关 API 详细信息,请参阅《AWS CLI 命令参考》中的 HeadBucket

CLI
AWS CLI

以下命令验证对名为 amzn-s3-demo-bucket 的存储桶的访问权限:

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

如果存储桶存在并且您可以访问它,则不返回任何输出。否则,会显示错误消息。例如:

A client error (404) occurred when calling the HeadBucket operation: Not Found
  • 有关 API 详细信息,请参阅《AWS CLI 命令参考》中的 HeadBucket

Go
适用于 Go V2 的 SDK
注意

查看 GitHub,了解更多信息。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 }
  • 有关 API 详细,请参阅《适用于 Go 的 AWS SDK API Reference》中的 HeadBucket

PowerShell
Tools for PowerShell V5

示例 1:当用户有权访问现有存储桶时,此命令对于该存储桶返回带有 HTTP 状态代码 200 OK 的输出。只有 S3 目录存储桶支持 BucketArn 参数。

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

输出

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

示例 2:对于不存在的存储桶,此命令会引发错误,并显示 HTTP 状态代码 NotFound。

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

输出

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

示例 3:对于用户无权访问的现有存储桶,此命令会引发错误,并显示 HTTP 状态代码 Forbidden。

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

输出

Get-S3HeadBucket: Error making request with Error Code Forbidden and Http Status Code Forbidden. No further error information was returned by the service.
  • 有关 API 详细信息,请参阅《AWS Tools for PowerShell Cmdlet Reference (V5)》中的 HeadBucket

Python
适用于 Python 的 SDK (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 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
  • 有关 API 详细信息,请参阅《AWS SDK for Python (Boto3) API Reference》中的 HeadBucket