Skip to content

Instantly share code, notes, and snippets.

@devjack
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devjack/559b707148e67bc1ff9d to your computer and use it in GitHub Desktop.
Save devjack/559b707148e67bc1ff9d to your computer and use it in GitHub Desktop.
Cache-Control headers for S3 Static sites
#!/bin/bash
### USAGE ###
## Sets $1's objects' Cache-control:max-age= header to $2.
## e.g. ./s3-header-hack.sh mybucket 60 // for 60 seconds.
s3Cmd() {
cmd=$1;
if type $cmd 2>/dev/null; then
S3CMD=$cmd;
else
if [ ! -x /tmp/s3cmd/s3cmd ]; then
echo "s3cmd is not installed. Installing..." >&1
cd /tmp/ >&1
rm -rf s3cmd >&1 ; # Remove existing temp install if required.
mkdir s3cmd && cd s3cmd >&1;
## I don't trust upstream repositories with my S3 keys
## Instead, I checkout a pre-vetted version that I know works
git clone https://github.com/s3tools/s3cmd.git . >&1
git reset --hard e7fad103ca2e485598f67a787c2789eb460dd9cb >&1
echo "Installed s3cmd to `pwd`" >&1
fi
S3CMD='python /tmp/s3cmd/s3cmd'
fi
}
expires() {
## Here we get to hack around with date since OSX screws with the params
offset=$1;
# http://stackoverflow.com/questions/3466166/how-to-check-if-running-in-cygwin-mac-or-linux
if [ "$(uname)" == "Darwin" ]; then
date -u -v"+$(echo $offset)S" +"%a, %d %b %Y %H:%M:%S"
elif [ "$(expr substr $(uname -s) 1 5)" = "Linux" ]; then
date -u -d"+$(echo $offset) seconds" +"%a, %d %b %Y %H:%M:%S"
elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW32_NT" ]; then
# I'm a lazy dev and officially don't support windows.
# Perhaps a cider infused night of dev will fix this, or a kind OSS contributor instead?
exit 1
fi
}
s3Cmd 's3cmd' # set the S3CMD variable.
echo "Using s3cmd: $S3CMD";
offset=$2;
##expiresHeader=$(expires $offset);
##
##
##if [ $? == 1 ]; then
## echo "Your OS is weird, fix me pl0x."
## exit 1
##fi
## Note: env vars are set by Codeship's S3 deploy
## -s enforces HTTPS
## I'm lazy and just set everything to 60s expire.
## For historical purposes, this is fun to play with!
#### --add-header="Expires:$expiresHeader"
$S3CMD --recursive modify \
--add-header="Cache-Control:max-age=$offset" \
--access_key=$AWS_ACCESS_KEY_ID \
--secret_key=$AWS_SECRET_ACCESS_KEY \
--region=$AWS_DEFAULT_REGION \
s3://$1/ \
-s
echo "One day, Codeship might add meta-data control to their s3 deployments :) "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment