Skip to content

Commit 2a7cc3e

Browse files
authored
Adding exception for bucket init creation in us-east-1 (#496)
1 parent a46d8ff commit 2a7cc3e

1 file changed

Lines changed: 24 additions & 15 deletions

File tree

ecs_composex/utils/init_s3.py

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,38 +2,47 @@
22
# SPDX-License-Identifier: MPL-2.0
33
# Copyright 2020-2021 John Mille <john@compose-x.io>
44

5+
from boto3.session import Session
56
from botocore.exceptions import ClientError
67

78
from ecs_composex.common import LOG
89

910

10-
def create_bucket(bucket_name, session):
11+
def create_bucket(bucket_name, session, no_location=False):
1112
"""
1213
Function that checks if the S3 bucket exists and if not attempts to create it.
1314
1415
:param bucket_name: name of the s3 bucket
1516
:type bucket_name: str
1617
:param session: boto3 session to use if wanted to override settings.
1718
:type session: boto3.session.Session
19+
:param no_location: Disable location constraint
1820
:returns: True/False, Returns whether the bucket exists or not for upload
1921
:rtype: bool
2022
"""
21-
client = session.client("s3")
22-
region = session.region_name
23-
location = {"LocationConstraint": region}
23+
s3_session = Session()
24+
client = s3_session.resource("s3")
25+
bucket = client.Bucket(bucket_name)
26+
params = {
27+
"ACL": "private",
28+
"Bucket": bucket_name,
29+
"ObjectLockEnabledForBucket": True,
30+
"CreateBucketConfiguration": {"LocationConstraint": s3_session.region_name},
31+
}
32+
if no_location or s3_session.region_name == "us-east-1":
33+
del params["CreateBucketConfiguration"]
2434
try:
25-
client.create_bucket(
26-
ACL="private",
27-
Bucket=bucket_name,
28-
ObjectLockEnabledForBucket=True,
29-
CreateBucketConfiguration=location,
30-
)
35+
bucket.create(**params)
3136
LOG.info(f"Bucket {bucket_name} successfully created.")
32-
except client.exceptions.BucketAlreadyExists:
37+
except client.meta.client.exceptions.BucketAlreadyExists:
3338
LOG.warning(f"Bucket {bucket_name} already exists.")
34-
except client.exceptions.BucketAlreadyOwnedByYou:
39+
except client.meta.client.exceptions.BucketAlreadyOwnedByYou:
3540
LOG.info(f"You already own the bucket {bucket_name}")
3641
except ClientError as error:
37-
LOG.error("Error whilst creating the bucket")
38-
LOG.error(error)
39-
raise
42+
print(error.response)
43+
if error.response["Error"]["Code"] == "InvalidLocationConstraint":
44+
create_bucket(bucket_name, session, True)
45+
else:
46+
LOG.error("Error whilst creating the bucket")
47+
LOG.error(error)
48+
raise

0 commit comments

Comments
 (0)