Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Script to deploy static website's build folder to AWS with necessary cache invalidations in S3 and in Cloudfront.

Automated Deployment to AWS S3

A helper script that will deploy build folder to s3 and invalidates caches of service worker, s3 and cloudfront to avoid not updating problem

# Enable printing executed commands
set x
trap "exit" INT

# Get AWS PROFILE, S3 Bucket and CloudFront Id from environment variables  or write it down statically

echo Profile: $aws_profile
echo S3_Bucket: $s3_bucket
echo CloudFront Distribution: $cf_id

if [ -z "$aws_profile" ]; then
  echo AWS_PROFILE not found
if [ -z "$s3_bucket" ]; then
  echo S3_BUCKET not found

#set env variable for aws cli
export AWS_PROFILE=$aws_profile

if [ ! -d "build" ]; then
    echo "${red}Build folder not found${reset}"
    exit 0;

echo Synching Build Folder: $s3_bucket...
aws s3 sync build/ s3://$s3_bucket --delete --cache-control max-age=31536000,public

echo Adjusting cache...
aws s3 cp s3://$s3_bucket/sw.js s3://$s3_bucket/sw.js --metadata-directive REPLACE --cache-control max-age=0,no-cache,no-store,must-revalidate --content-type application/javascript --acl public-read
aws s3 cp s3://$s3_bucket/index.html s3://$s3_bucket/index.html --metadata-directive REPLACE --cache-control max-age=0,no-cache,no-store,must-revalidate --content-type text/html --acl public-read

if [ ! -z "$cf_id" ]; then
    echo Invalidating cloudfront cache
    aws cloudfront create-invalidation --distribution-id $cf_id --paths "/*"

Run the command in terminal

$ sh

Note: AWS_PROFILE must have access permissions to followings

Example policy:

      "Effect": "Allow",
      "Action": ["s3:ListBucket", "s3:PutObject", "s3:PutObjectAcl", "s3:DeleteObject"],
      "Resource": [
      "Action": [
      "Effect": "Allow",
      "Resource": "*"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment