Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ coverage.xml
venv
env2
env3
boto3_venv/


# Virtualenv support files and directories
.python-version
Expand Down
26 changes: 15 additions & 11 deletions docs/source/guide/s3-example-creating-buckets.rst
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,22 @@ The name of an Amazon S3 bucket must be unique across all regions of the AWS
platform. The bucket can be located in a specific region to minimize latency
or to address regulatory requirements.

.. note::
The ``LocationConstraint`` value is used to specify the region where a bucket
will be created. S3 requires ``LocationConstraint`` to be specified when creating
buckets using a client in regions other than ``us-east-1``. When no region is
specified, ``us-east-1`` is used by default. The example below ensures the S3
client is created in the same region as the bucket to avoid a
``IllegalLocationConstraintException`` error.

.. code-block:: python

import logging
import boto3
from botocore.exceptions import ClientError


def create_bucket(bucket_name, region=None):
def create_bucket(bucket_name, region='us-east-1'):
"""Create an S3 bucket in a specified region

If a region is not specified, the bucket is created in the S3 default
Expand All @@ -47,20 +55,17 @@ or to address regulatory requirements.

# Create bucket
try:
if region is None:
s3_client = boto3.client('s3')
s3_client.create_bucket(Bucket=bucket_name)
else:
s3_client = boto3.client('s3', region_name=region)
location = {'LocationConstraint': region}
s3_client.create_bucket(Bucket=bucket_name,
CreateBucketConfiguration=location)
bucket_config = {}
s3_client = boto3.client('s3', region_name=region)
if region != "us-east-1":
bucket_config["CreateBucketConfiguration"] = {"LocationConstraint": region}

s3_client.create_bucket(Bucket=bucket_name, **bucket_config)
except ClientError as e:
logging.error(e)
return False
return True


List existing buckets
=====================

Expand All @@ -76,4 +81,3 @@ List all the existing buckets for the AWS account.
print('Existing buckets:')
for bucket in response['Buckets']:
print(f' {bucket["Name"]}')