Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check that a AWS S3 bucket exists?

Simple question here? ...

How can I check with boto that a AWS bucket exists? ... preferably by providing the path? ...

here is the approach I feel like taking:

def bucket_exists(self, bucket_name):
    connection = boto.s3.connection.S3Connection('<aws access key>', '<aws secret key>')
    buckets = connection.get_all_buckets()
    for bucket in buckets:
        bucket_name = bucket.name
        # Bucket existence logic here
        # submit boto request
        ie:. exists = boto.get_bucket(bucket_name, validate=True)
        if exists:
            return True
        else:
            return False

In the code above I am interested to find if a bucket exists amongst the buckets that this AWS Account owns ...

IS there a better way to find out if a bucket exists? How would I implement a better way?

Thanks

like image 362
Becks Avatar asked May 15 '15 19:05

Becks


2 Answers

From the documentation:

If you are unsure if the bucket exists or not, you can use the S3Connection.lookup method, which will either return a valid bucket or None.

So this is the best option:

bucket = connection.lookup('this-is-my-bucket-name')
if not bucket:
    print "This bucket doesn't exist."
like image 189
lmo Avatar answered Oct 29 '22 16:10

lmo


You could just try and load the bucket (as you are doing now). By default the method is set to validate if the bucket exists.

You could also just try to "lookup" the bucket. The method will raise an S3ResponseError.

Ether way, you'll have to make an API call so I think you're left to personal preference here (whether you like dealing with exceptions, or simply checking for None).

So you have a couple of options here:

bucket = connection.lookup('this-is-my-bucket-name')
if bucket is None:
    print "This bucket doesn't exist."

Or:

try:
    bucket = connection.get_bucket('this-is-my-bucket-name')
except S3ResponseError:
    print "This bucket doesn't exist."
like image 41
devonlazarus Avatar answered Oct 29 '22 17:10

devonlazarus