|
2 | 2 | # SPDX-License-Identifier: MPL-2.0 |
3 | 3 | # Copyright 2020-2021 John Mille <john@compose-x.io> |
4 | 4 |
|
| 5 | +from boto3.session import Session |
5 | 6 | from botocore.exceptions import ClientError |
6 | 7 |
|
7 | 8 | from ecs_composex.common import LOG |
8 | 9 |
|
9 | 10 |
|
10 | | -def create_bucket(bucket_name, session): |
| 11 | +def create_bucket(bucket_name, session, no_location=False): |
11 | 12 | """ |
12 | 13 | Function that checks if the S3 bucket exists and if not attempts to create it. |
13 | 14 |
|
14 | 15 | :param bucket_name: name of the s3 bucket |
15 | 16 | :type bucket_name: str |
16 | 17 | :param session: boto3 session to use if wanted to override settings. |
17 | 18 | :type session: boto3.session.Session |
| 19 | + :param no_location: Disable location constraint |
18 | 20 | :returns: True/False, Returns whether the bucket exists or not for upload |
19 | 21 | :rtype: bool |
20 | 22 | """ |
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"] |
24 | 34 | try: |
25 | | - client.create_bucket( |
26 | | - ACL="private", |
27 | | - Bucket=bucket_name, |
28 | | - ObjectLockEnabledForBucket=True, |
29 | | - CreateBucketConfiguration=location, |
30 | | - ) |
| 35 | + bucket.create(**params) |
31 | 36 | LOG.info(f"Bucket {bucket_name} successfully created.") |
32 | | - except client.exceptions.BucketAlreadyExists: |
| 37 | + except client.meta.client.exceptions.BucketAlreadyExists: |
33 | 38 | LOG.warning(f"Bucket {bucket_name} already exists.") |
34 | | - except client.exceptions.BucketAlreadyOwnedByYou: |
| 39 | + except client.meta.client.exceptions.BucketAlreadyOwnedByYou: |
35 | 40 | LOG.info(f"You already own the bucket {bucket_name}") |
36 | 41 | 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