Is it possible to check if a bucket name already exists?

Question:

I have a method that needs a name to create a new bucket.

And I want to show a message “bucket name already exist” if the bucket name already exist.

It is possible to check if a bucket name already exists?

def createBucket(bucketName):
    c = boto.s3.connect_to_region("us-east-1")
    # if bucketName exist: 
        print "bucket name already exist"
    else:
        bucket = c.create_bucket(bucketName)

bucket = createBucket(raw_input("Bucket name: "))   
Asked By: techman

||

Answers:

Amazon Web Services will give you a custom S3CreateError exception when the bucket name per location has already been taken.

>>> bucket = conn.create_bucket('mybucket')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "boto/connection.py", line 285, in create_bucket
    raise S3CreateError(response.status, response.reason)
boto.exception.S3CreateError: S3Error[409]: Conflict

You could use that exception for your case.

from boto.exception import S3CreateError

    def createBucket(bucketName):
        c = boto.s3.connect_to_region("us-east-1")
        try:
            bucket = c.create_bucket(bucketName)
        except S3CreateError:
            print "bucket name already exist"

    bucket = createBucket(raw_input("Bucket name: ")) 
Answered By: no coder

lookup should work (though I can’t try now).

Answered By: Stefan Pochmann

assumes boto.cfg is configured for region, secure, access, etc.

from boto.s3.connection import S3Connection
conn = S3Connection()
if conn.lookup('bucketnamehere') is not None:
     print('bucket already exists')

if your boto does not support conn.lookup, you may want to use head instead of get (see : http://boto.readthedocs.org/en/latest/ref/s3.html#module-boto.s3.connection )

try:
    conn.head_bucket('bucketnamehere')

except S3ResponseError as error:
    print('bucket already exists: {0}'.format(error))
Answered By: cgseller

I had the same question but a) using boto3 and b) I care about the difference between "doesn’t exist in anyone’s account" and "I just don’t have access". This is what what I found seems to work:

import boto3
s3 = boto3.Session().resource('S3')
list(s3.Bucket("private").objects.all())
# Thank you whoever created that bucket! 
# -> throws "An error occurred (AccessDenied)..."

list(s3.Bucket(some_name_that_does_not_exists).objects.all())
# -> throws "An error occurred (NoSuchBucket)..."
Answered By: BCS