"""Idempotently create the private attachment buckets with the bootstrap identity.""" import os import time import boto3 from botocore.exceptions import ClientError def main(): client = boto3.client( 's3', endpoint_url=os.environ['S3_ENDPOINT'], aws_access_key_id=os.environ['S3_ADMIN_ACCESS_KEY'], aws_secret_access_key=os.environ['S3_ADMIN_SECRET_KEY'], region_name='us-east-1', verify=os.environ['S3_CA_CERT'], config=boto3.session.Config(s3={'addressing_style': 'path'}, retries={'max_attempts': 2}), ) buckets = ('attachments-staging', 'attachments-original', 'attachments-variants') last_error = None for attempt in range(60): try: for bucket in buckets: try: client.head_bucket(Bucket=bucket) except ClientError as exc: if exc.response.get('ResponseMetadata', {}).get('HTTPStatusCode') != 404: raise try: client.create_bucket(Bucket=bucket) except ClientError as exc: if exc.response.get('Error', {}).get('Code') not in ('BucketAlreadyOwnedByYou', 'BucketAlreadyExists'): raise print('PASS: private S3 buckets are provisioned: ' + ', '.join(buckets)) return except Exception as exc: last_error = exc time.sleep(min(1 + attempt, 3)) raise RuntimeError('S3 bucket provisioning failed') from last_error if __name__ == '__main__': main()