In this blog you will learn about how to deploy your Gatsby site to AWS S3 bucket.
There are several ways to deploy it:
- AWS CLI
- AWS CLI with
gatsby-plugin-s3
plugin - Circleci
1. Using AWS CLI
Lets install aws cli globally first.
npm i aws-cli -g
Then we need to configure using the below command and enter our AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
aws configure
We will now create a .env
file in our project root directory ( Make sure dotenv npm package is installed ) and add the keys.
AWS_BUCKET_NAME=xxx
Then we can create a directory called bin
in our project root and create two files deploy.js
and deploy.sh
mkdir bin
touch bin/deploy.js bin/deploy.sh
Now add this to deploy.js
const fs = require( 'fs' );
// Give executable permission.
fs.chmodSync( 'bin/deploy.sh', '0755' );
And add this to deploy.sh
# Get the AWS_BUCKET_NAME value as a variable $AWS_BUCKET_NAME
AWS_BUCKET_NAME=$(grep AWS_BUCKET_NAME .env | cut -d '=' -f2);
# Clean the cache, run build and deploy the public directory and exclude the uploads folder.
npm run clean && npm run build && aws s3 sync public s3://$AWS_BUCKET_NAME/ --exclude "folder-name-you-want-to-exclude" --acl public-read;
Now our package.json should have following scripts:
"scripts": {
"build": "gatsby build",
"deploy": "node bin/deploy.js && ./bin/deploy.sh",
"clean": "gatsby clean",
},
When we run npm run deploy
will give our deploy.sh
executable permission in deploy.js
and then clean cache, run build and then push the local gatsby files from local pubic directory to s3 bucket root directory. You can also exclude any folder you dont want to be overriden in the bucket.
npm run deploy
Instead of running npm run deploy
You can also directly run the below command from your terminal ( after npm run build ). Make sure to replace $AWS_BUCKET_NAME
with your bucket name.
aws s3 sync public s3://$AWS_BUCKET_NAME/ --exclude "folder-name-you-want-to-exclude" --acl public-read
2. Using AWS CLI with gatsby-plugin-s3
After installing and configuring AWS using npm i aws-cli -g
and aws configure
, and creating .env
file as explained above, you can then install the following plugin
npm i gatsby-plugin-s3
Now add the following to your gatsby-config.js
plugins: [
{
resolve: `gatsby-plugin-s3`,
options: {
bucketName: `${ process.env.AWS_BUCKET_NAME }`
},
},
]
Now add the following script to your package.json
"scripts": {
"build": "gatsby build",
"deploy": "npm run build && gatsby-plugin-s3 deploy"
}
3. Using AWS CLI and Circleci ( Continuous Integration )
Follow the steps explained in Point no 1 first for installing and setting up aws cli.
First you create an account on Circleci.
Create context with AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
Then create a circleci.yaml file
Bonus –
a. AWS CLI Command
aws s3 ls s3://mybucket