Common aws s3 sync examples
Handy aws s3 sync command examples for uploading, downloading, mirroring with --delete, filtering, cache headers and dry runs, from deploying static sites to S3.
The aws s3 sync command from the AWS CLI copies files between a local directory and an S3 bucket, or between two buckets, transferring only what has changed. It is the command I reach for most when deploying a static website to S3, and it pairs well with a CloudFront invalidation to push the new version live.
Uploading a directory to a bucket
aws s3 sync ./_site s3://my-bucket
This uploads everything under _site that is new or changed. Files already present and unchanged in the bucket are skipped, which keeps repeated deploys fast.
Downloading a bucket to a directory
aws s3 sync s3://my-bucket ./local-copy
Removing files that no longer exist
By default sync never deletes. Add --delete to remove objects from the destination that are no longer in the source, so the bucket becomes an exact mirror of your build:
aws s3 sync ./_site s3://my-bucket --delete
Including and excluding files
aws s3 sync ./_site s3://my-bucket --exclude "*.map" --exclude ".DS_Store"
The --exclude and --include filters are applied in order, so you can exclude broadly and then include back the exceptions:
aws s3 sync ./assets s3://my-bucket --exclude "*" --include "*.jpg" --include "*.png"
Setting cache headers as you upload
aws s3 sync ./_site s3://my-bucket --cache-control "max-age=31536000,public"
Handy for fingerprinted assets you want cached hard. For files that change at the same URL, such as an index.html, run a second sync over just those with a shorter max-age.
Previewing before you commit
aws s3 sync ./_site s3://my-bucket --delete --dryrun
The --dryrun flag prints exactly what would be uploaded and deleted without changing anything, which is worth doing before any sync that uses --delete.
For copying single files, doing a one-off recursive copy, or streaming an object rather than mirroring a whole directory, see common aws s3 cp examples.