#!/bin/sh set -eu # Idempotently provisions the S3 docs bucket with sane defaults. # # This script is intended for CI/CD (Gitea Actions) or operator usage. # It is safe to run repeatedly: # - If the bucket exists, it will NOT recreate it. # - It will (re)apply public-access-block and optional versioning/lifecycle. # # Required env: # - S3_ENDPOINT # - S3_REGION # - S3_BUCKET_DOCS # # Optional env: # - S3_ENABLE_VERSIONING (true/false; default false) # - S3_LIFECYCLE_JSON (path; default docs/usage/s3_lifecycle_docs_default.json) # # Credentials: # - AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY (or AWS_PROFILE) # # Notes: # - Some S3-compatible providers ignore LocationConstraint; this script tries to be compatible. need() { name="$1" val="$(printenv "$name" 2>/dev/null || true)" if [ -z "$val" ]; then echo "missing env: $name" >&2 exit 2 fi } need S3_ENDPOINT need S3_REGION need S3_BUCKET_DOCS if ! command -v aws >/dev/null 2>&1; then echo "missing dependency: aws (AWS CLI v2 recommended)" >&2 exit 2 fi export AWS_EC2_METADATA_DISABLED=true export AWS_DEFAULT_REGION="$S3_REGION" export AWS_REGION="$S3_REGION" endpoint_args="--endpoint-url=$S3_ENDPOINT" bucket="$S3_BUCKET_DOCS" echo "== ensure bucket exists ==" if aws s3api head-bucket $endpoint_args --bucket "$bucket" >/dev/null 2>&1; then echo "bucket exists: $bucket" else # Try create-bucket without LocationConstraint first (works for many S3-compatible providers). if aws s3api create-bucket $endpoint_args --bucket "$bucket" >/dev/null 2>&1; then echo "created bucket: $bucket" else # Fallback for AWS-style regions. aws s3api create-bucket $endpoint_args --bucket "$bucket" \ --create-bucket-configuration "LocationConstraint=$S3_REGION" >/dev/null echo "created bucket (with location constraint): $bucket" fi fi echo "== apply public access block ==" aws s3api put-public-access-block $endpoint_args --bucket "$bucket" --public-access-block-configuration \ "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true" >/dev/null S3_ENABLE_VERSIONING="${S3_ENABLE_VERSIONING:-false}" if [ "$S3_ENABLE_VERSIONING" = "true" ] || [ "$S3_ENABLE_VERSIONING" = "1" ]; then echo "== enable versioning ==" aws s3api put-bucket-versioning $endpoint_args --bucket "$bucket" --versioning-configuration Status=Enabled >/dev/null fi echo "== apply lifecycle (optional) ==" S3_LIFECYCLE_JSON="${S3_LIFECYCLE_JSON:-docs/usage/s3_lifecycle_docs_default.json}" if [ -f "$S3_LIFECYCLE_JSON" ]; then aws s3api put-bucket-lifecycle-configuration \ --endpoint-url "$S3_ENDPOINT" \ --bucket "$bucket" \ --lifecycle-configuration "file://$S3_LIFECYCLE_JSON" >/dev/null else echo "lifecycle file missing, skipping: $S3_LIFECYCLE_JSON" >&2 fi echo "ok: provisioned bucket $bucket"