@@ -27,14 +27,22 @@ The name of an Amazon S3 bucket must be unique across all regions of the AWS
2727platform. The bucket can be located in a specific region to minimize latency
2828or to address regulatory requirements.
2929
30+ .. note ::
31+ The ``LocationConstraint `` value is used to specify the region where a bucket
32+ will be created. S3 requires ``LocationConstraint `` to be specified when creating
33+ buckets using a client in regions other than ``us-east-1 ``. When no region is
34+ specified, ``us-east-1 `` is used by default. The example below ensures the S3
35+ client is created in the same region as the bucket to avoid a
36+ ``IllegalLocationConstraintException `` error.
37+
3038.. code-block :: python
3139
3240 import logging
3341 import boto3
3442 from botocore.exceptions import ClientError
3543
3644
37- def create_bucket (bucket_name , region = None ):
45+ def create_bucket (bucket_name , region = ' us-east-1 ' ):
3846 """ Create an S3 bucket in a specified region
3947
4048 If a region is not specified, the bucket is created in the S3 default
@@ -47,20 +55,17 @@ or to address regulatory requirements.
4755
4856 # Create bucket
4957 try :
50- if region is None :
51- s3_client = boto3.client(' s3' )
52- s3_client.create_bucket(Bucket = bucket_name)
53- else :
54- s3_client = boto3.client(' s3' , region_name = region)
55- location = {' LocationConstraint' : region}
56- s3_client.create_bucket(Bucket = bucket_name,
57- CreateBucketConfiguration = location)
58+ bucket_config = {}
59+ s3_client = boto3.client(' s3' , region_name = region)
60+ if region != ' us-east-1' :
61+ bucket_config[' CreateBucketConfiguration' ] = {' LocationConstraint' : region}
62+
63+ s3_client.create_bucket(Bucket = bucket_name, ** bucket_config)
5864 except ClientError as e:
5965 logging.error(e)
6066 return False
6167 return True
6268
63-
6469 List existing buckets
6570=====================
6671
@@ -76,4 +81,3 @@ List all the existing buckets for the AWS account.
7681 print (' Existing buckets:' )
7782 for bucket in response[' Buckets' ]:
7883 print (f ' { bucket[" Name" ]} ' )
79-
0 commit comments