AWS SDK 또는 CLI와 함께 HeadBucket 사용 - AWS SDK 코드 예제

AWS SDK 예제 GitHub 리포지토리에 더 많은 AWS문서 SDK 예제가 있습니다.

AWS SDK 또는 CLI와 함께 HeadBucket 사용

다음 코드 예시는 HeadBucket의 사용 방법을 보여 줍니다.

Bash
Bash 스크립트와 함께 AWS CLI사용
참고

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
SDK for Go V2
참고

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 세부 정보는 AWS SDK for Go API 참조HeadBucket을 참조하십시오.

PowerShell
Tools for PowerShell V5

예제 1: 이 명령에서는 사용자에게 액세스 권한이 있을 때 기존 버킷에 대해 HTTP 상태 코드 200 OK로 출력을 반환합니다. BucketArn 파라미터는 S3 디렉터리 버킷에서만 지원됩니다.

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 참조(V5)HeadBucket을 참조하세요.

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 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 세부 정보는 AWSSDK for Python (Boto3) API 참조HeadBucket를 참조하십시오.