forked from mtusi2026/mtusi2026lab5
48 lines
1.4 KiB
Python
48 lines
1.4 KiB
Python
#!/usr/bin/env python3
|
|
import logging
|
|
import os
|
|
from pathlib import Path
|
|
|
|
import boto3
|
|
from botocore.config import Config
|
|
from botocore.exceptions import ClientError
|
|
|
|
|
|
LOGGER = logging.getLogger("messenger.s3.bootstrap")
|
|
|
|
|
|
def secret(name: str) -> str:
|
|
direct = os.getenv(name)
|
|
if direct:
|
|
return direct
|
|
file_path = os.getenv(name + "_FILE")
|
|
if file_path:
|
|
return Path(file_path).read_text(encoding="utf-8").strip()
|
|
raise RuntimeError(f"Set {name} or {name}_FILE")
|
|
|
|
|
|
def main():
|
|
client = boto3.client(
|
|
"s3",
|
|
endpoint_url=os.getenv("S3_ENDPOINT", "http://s3:8333"),
|
|
region_name="us-east-1",
|
|
aws_access_key_id=secret("S3_ADMIN_ACCESS_KEY_ID"),
|
|
aws_secret_access_key=secret("S3_ADMIN_SECRET_ACCESS_KEY"),
|
|
config=Config(connect_timeout=2, read_timeout=5, retries={"max_attempts": 3}),
|
|
)
|
|
bucket = os.getenv("S3_BUCKET", "messenger-attachments")
|
|
try:
|
|
client.head_bucket(Bucket=bucket)
|
|
except ClientError as exc:
|
|
status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
|
if status != 404:
|
|
raise
|
|
client.create_bucket(Bucket=bucket)
|
|
client.put_bucket_acl(Bucket=bucket, ACL="private")
|
|
LOGGER.info("private S3 bucket bootstrap completed")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
logging.basicConfig(level="INFO", format="%(levelname)s %(message)s")
|
|
main()
|