BASH

Automating Static Site Deployment to AWS S3

Deploy your static web projects to Amazon S3 buckets efficiently using the AWS CLI within a bash script, including synchronization, cache control, and public-read access.

#!/bin/bash

# Pre-requisites:
# 1. AWS CLI installed and configured (aws configure)
# 2. An S3 bucket created for your static site

# Configuration
BUCKET_NAME="your-static-site-bucket-name" # REPLACE WITH YOUR S3 BUCKET NAME
DIST_DIR="./dist" # Path to your static site's build output directory

# --- Start Deployment ---

if [ ! -d "$DIST_DIR" ]; then
  echo "Error: Distribution directory '$DIST_DIR' not found. Please build your project first." >&2
  exit 1
fi

echo "Starting deployment to s3://$BUCKET_NAME/ from $DIST_DIR"

# Synchronize local 'dist' directory with S3 bucket
# --delete: Removes S3 objects that don't have a corresponding local file
# --acl public-read: Makes uploaded objects publicly readable (essential for static sites)
# --cache-control: Sets browser caching headers for optimized performance
aws s3 sync "$DIST_DIR" "s3://$BUCKET_NAME" \
  --delete \
  --acl public-read \
  --cache-control "max-age=3600, public"

if [ $? -eq 0 ]; then
  echo "
Deployment to s3://$BUCKET_NAME completed successfully!"
  echo "Your site should be available at: http://$BUCKET_NAME.s3-website-YOUR_REGION.amazonaws.com/ (replace YOUR_REGION)"
else
  echo "
Error: AWS S3 deployment failed." >&2
  exit 1
fi
How it works: This script automates the deployment of static web projects to an AWS S3 bucket. It requires the AWS CLI to be installed and configured. The script first checks if the specified distribution directory (`./dist` by default) exists. It then uses `aws s3 sync` to upload local files to the S3 bucket, ensuring that only changed files are uploaded and deleted files are removed from the bucket (`--delete`). Essential flags like `--acl public-read` are used to make the content accessible via the web, and `--cache-control` sets browser caching headers for performance. This provides a robust, scriptable deployment mechanism for static sites.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs