Skip to content

Instantly share code, notes, and snippets.

@aindong
Created June 20, 2019 04:45
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 aindong/62b88d592fe96f5f5eb8c7eb0b85d43d to your computer and use it in GitHub Desktop.
Save aindong/62b88d592fe96f5f5eb8c7eb0b85d43d to your computer and use it in GitHub Desktop.
Build and deploy a create-react-app to s3 and cloudfront
#!/bin/bash
## Colors for cli output messages
ERROR=`tput setaf 1`
SUCCESS=`tput setaf 2`
PC=`tput setaf 3`
NC=`tput sgr0`
## Available choices on args
## You can create as many project as you like for choices
CHOICES='^(project1|project2)$'
## Deployment credentials
BUCKETNAME=
GIT_BRANCH=release
CLOUDFRONT=$2
## AWS Profile
PROFILE=
if [[ ! $1 =~ $CHOICES ]]; then
echo "${ERROR}Noesss!!${NC} UNKNOWN ARGUMENT"
exit 0
fi
project=$1
echo "${PC}Preparing to deploy:" $project
# Assign s3 bucket
BUCKETNAME=${project}
echo "${PC}Pulling the ${GIT_BRANCH} branch"
## Get the release branch
git checkout $GIT_BRANCH
git pull origin $GIT_BRANCH
echo "${PC}Building the ${project} project"
## Create a build for selected project
npm run build
## Sync the build output to s3 bucket
aws s3 sync build s3://$BUCKETNAME --delete --cache-control \
max-age=604800,public --profile $PROFILE
## A serviceworker should not stay on cache or everything will break
aws s3 cp s3://$BUCKETNAME/service-worker.js s3://$BUCKETNAME/service-worker.js \
--metadata-directive REPLACE --cache-control max-age=0,no-cache,no-store,must-revalidate \
--content-type application/javascript --acl public-read --profile $PROFILE
## The main index.html should not stay on cache because it should reference the new js
aws s3 cp s3://$BUCKETNAME/index.html s3://$BUCKETNAME/index.html --metadata-directive REPLACE \
--cache-control max-age=0,no-cache,no-store,must-revalidate --content-type text/html \
--acl public-read --profile $PROFILE
echo "${PC}Creating invalidation for cloudfront"
id = $(aws cloudfront create-invalidation --distribution-id $CLOUDFRONT --paths "/*" --profile $PROFILE | egrep Id | awk -F'"' '{ print $4}')
echo "${PC}Waiting for invalidation of ${id}"
## Wait for invalidation to finish
aws cloudfront wait invalidation-completed --id $id --distribution-id $CLOUDFRONT && echo "${SUCCESS}Invalidation $id completed"
echo "${SUCCESS} Project ${NC}${project} ${SUCCESS}was Deployed successfully!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment