How can I easily determine if a Boto 3 S3 bucket resource exists?

后端 未结 6 1567
滥情空心
滥情空心 2020-12-29 01:34

For example, I have this code:

import boto3

s3 = boto3.resource(\'s3\')

bucket = s3.Bucket(\'my-bucket-name\')

# Does it exist???
6条回答
  •  爱一瞬间的悲伤
    2020-12-29 02:13

    I tried Daniel's example and it was really helpful. Followed up the boto3 documentation and here is my clean test code. I have added a check for '403' error when buckets are private and return a 'Forbidden!' error.

    import boto3, botocore
    s3 = boto3.resource('s3')
    bucket_name = 'some-private-bucket'
    #bucket_name = 'bucket-to-check'
    
    bucket = s3.Bucket(bucket_name)
    def check_bucket(bucket):
        try:
            s3.meta.client.head_bucket(Bucket=bucket_name)
            print("Bucket Exists!")
            return True
        except botocore.exceptions.ClientError as e:
            # If a client error is thrown, then check that it was a 404 error.
            # If it was a 404 error, then the bucket does not exist.
            error_code = int(e.response['Error']['Code'])
            if error_code == 403:
                print("Private Bucket. Forbidden Access!")
                return True
            elif error_code == 404:
                print("Bucket Does Not Exist!")
                return False
    
    check_bucket(bucket)
    

    Hope this helps some new into boto3 like me.

提交回复
热议问题