Skip to content

Instantly share code, notes, and snippets.

@Sauloxd
Last active March 30, 2019 11:43
Show Gist options
  • Save Sauloxd/12e4ef644dd2030fe439f47e474d2aa3 to your computer and use it in GitHub Desktop.
Save Sauloxd/12e4ef644dd2030fe439f47e474d2aa3 to your computer and use it in GitHub Desktop.
How to deploy your static asset to S3 using travis CD
language: node_js
cache:
directories:
- node_modules
script:
- npm test
- npm run build
before_deploy: pip install --user awscli
deploy:
provider: script
script: ~/.local/bin/aws s3 sync build s3://$BUCKET_NAME --region=$BUCKET_REGION --delete && ~/.local/bin/aws s3 cp s3://$BUCKET_NAME/index.html s3://$BUCKET_NAME/index.html --metadata-directive REPLACE --cache-control max-age=0 --region=$BUCKET_REGION
acl: public_read
bucket: "$BUCKET_NAME"
region: "$BUCKET_REGION"
local_dir: build
skip_cleanup: true
on:
branch: master
env:
global:
- BUCKET_NAME=saulo.dev
- BUCKET_REGION=us-east-1
- secure: [encrypt AWS_ACCESS_KEY_ID] # travis login --pro && travis encrypt AWS_ACCESS_KEY_ID=<<replace-here>> --add --com
- secure: [encrypt AWS_SECRET_ACCESS_KEY] # travis login --pro && travis encrypt AWS_SECRET_ACCESS_KEY=<<replace-here>> --add --com
@Sauloxd
Copy link
Author

Sauloxd commented Mar 30, 2019

Tip, create a IAM role in your AWS to handle your S3 deployment.

  1. Create a group of members that will be able to deploy to S3:
    AWS > IAM > Create new Group > { GroupName: 'CICD' } > { policies: ['AmazonS3FullAccess'] }
  2. Add a new user named 'travis' to this group:
    AWS > IAM > Users > Add Users > { UserName: 'travis', AccessType: 'programmatic access' } > Add to 'CICD' Group > Get Key/SecretKey pair

@Sauloxd
Copy link
Author

Sauloxd commented Mar 30, 2019

Script meaning:

BUILD_DIR=build
 ~/.local/bin/aws s3 sync $BUILD_DIR s3://$BUCKET_NAME \
  --region=$BUCKET_REGION 
  --delete

Uploads all in build directory (mine is build, yours can be dist, lib, bleus, change accordingly), in the proper bucket region, --deleting everything in the bucket beforehand.

~/.local/bin/aws s3 cp s3://$BUCKET_NAME/index.html s3://$BUCKET_NAME/index.html 
  --metadata-directive REPLACE \
  --cache-control max-age=0 \
  --region=$BUCKET_REGION

This is used to update the index.html cache-control metadata so whenever a user requests index.html it will always get a fresh one (instead of the cached version)

@Sauloxd
Copy link
Author

Sauloxd commented Mar 30, 2019

Also ~/.local/bin/aws is only available due to before_deploy: pip install --user awscli

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