Search code examples
python-3.xamazon-web-servicesamazon-s3boto3

AWS boto3 can't create a bucket - Python


Iam facing an issue that I my code is not successfully to create bucket in AWS using boto3 python. Below my code

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

def create_bucket(bucket_name, region='us-east-1'):
    if region is None:
        s3.create_bucket(Bucket=bucket_name)
    else:
        location = { 'LocationConstraint': region }
        s3.create_bucket(Bucket=bucket_name,
                         CreateBucketConfiguration=location)

create_bucket('my-testing-bucket')

When I run, I got this error botocore.exceptions.ClientError: An error occurred (IllegalLocationConstraintException) when calling the CreateBucket operation: The us-east-1 location constraint is incompatible for the region specific endpoint this request was sent to.. Will be happy to get your help. Thanks

I want to create a bucket in AWS S3 using boto3 python. But I got an error in my code


Solution

  • There's a couple of issues:

    • When creating a bucket, the boto3 client needs to connect to the same region as where the bucket is being created. Therefore, you will need to pass a region_name when creating the S3 client.
    • The default value of the region parameter in your create_bucket() function will pass a value of 'us-east-1', so region will never be null

    Here's some updated code:

    import boto3
    
    region = 'us-east-1'
    
    s3 = boto3.resource('s3', region_name=region)
    
    def create_bucket(bucket_name, region='us-east-1'):
        if region == 'us-east-1':
            s3.create_bucket(Bucket=bucket_name)
        else:
            location = { 'LocationConstraint': region }
            s3.create_bucket(Bucket=bucket_name,
                             CreateBucketConfiguration=location)
    
    create_bucket('my-new-bucket')