Automate React App Deployment to AWS S3 with a Simple Bash Script
Tags: aws, s3, shellscript, automation
Published: 2024-05-29 16:14:28

Deploying your web applications can often be a tedious and error-prone process, especially when done manually. However, with the power of automation, you can streamline this process and ensure consistent and reliable deployments every time. In this blog post, we'll explore a simple Bash script that automates the deployment of a React app to an AWS S3 bucket, making it publicly accessible as a static website.

Prerequisites
Before you begin, make sure you have the following:

- AWS CLI installed and configured with the appropriate permissions.
- Node.js and npm installed.
- A React application ready to deploy.


Here's a breakdown of the Bash script that automates the deployment of a React app to an AWS S3 bucket:

```
#!/bin/bash
AWS_REGION="us-east-1"
# Build React app
npm install
npm run build
# Ask user for the bucket name
echo "Enter a unique bucket name: "
read  BUCKET_NAME
# Check if bucket exists
BUCKET_EXISTS=$(aws s3api head-bucket --bucket $BUCKET_NAME --query 'Code' --output text 2>/dev/null)
if [ "$BUCKET_EXISTS" = "200" ]; then
    echo "Bucket $BUCKET_NAME already exists. Do you want to sync the code? (y/n)"
    read SYNC_OPTION
    if [ "$SYNC_OPTION" == "y" ]; then
        # Upload build to S3
        aws s3 sync build/ s3://$BUCKET_NAME
        echo "Code synced to S3"
    fi
    echo "Your React app is deployed at: http://$BUCKET_NAME.s3-website.$AWS_REGION.amazonaws.com"
    echo "Open default browser"
    # Open default browser
    if [[ "$OSTYPE" == "darwin"* ]]; then
        open "http://$BUCKET_NAME.s3-website.$AWS_REGION.amazonaws.com"
    elif [[ "$OSTYPE" == "msys"* ]]; then
        start "http://$BUCKET_NAME.s3-website.$AWS_REGION.amazonaws.com"
    fi
else
    # Set bucket policy for public access
    BUCKET_POLICY='{
        "Version": "2012-10-17",
        "Statement": [
            {
                "Sid": "PublicReadGetObject",
                "Effect": "Allow",
                "Principal": "*",
                "Action": [
                    "s3:GetObject"
                ],
                "Resource": [
                    "arn:aws:s3:::'$BUCKET_NAME'/*"
                ]
            }
        ]
    }'
    # Create S3 bucket
    aws s3api create-bucket --bucket $BUCKET_NAME --region $AWS_REGION
    echo "bucket created $BUCKET_NAME"
    # Enable static website hosting
    aws s3 website s3://$BUCKET_NAME/ --index-document index.html
    echo "Enable static website hosting"
    # Disable "Block all public access"
    aws s3api put-public-access-block --bucket $BUCKET_NAME --public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"
    echo "Disable 'Block all public access'"
    # Set bucket policy for public access
    aws s3api put-bucket-policy --bucket $BUCKET_NAME --policy "$BUCKET_POLICY"
    # Upload build to S3
    aws s3 sync build/ s3://$BUCKET_NAME
    echo "Upload build to S3"
    echo "Your React app is deployed at: http://$BUCKET_NAME.s3-website.$AWS_REGION.amazonaws.com"
    echo "Open default browser"
    # Open default browser
    if [[ "$OSTYPE" == "darwin"* ]]; then
        open "http://$BUCKET_NAME.s3-website.$AWS_REGION.amazonaws.com"
    elif [[ "$OSTYPE" == "msys"* ]]; then
        start "http://$BUCKET_NAME.s3-website.$AWS_REGION.amazonaws.com"
    fi
fi
```


Here's what the script does:

1. Set the AWS Region: The script sets the AWS region to us-east-1, but you can modify this to your desired region.
2. Build the React App: The script runs npm install and npm run build to install dependencies and build the React app.
3. Prompt for Bucket Name: The user is prompted to enter a unique bucket name, which is stored in the BUCKET_NAME variable.
4. Checking for Existing Bucket: Before proceeding with the deployment, the script checks if the specified bucket already exists using the AWS CLI command aws s3api head-bucket. If the bucket exists, the user is prompted to confirm whether they want to sync the code with the existing bucket or not.
5. Syncing with Existing Bucket: If the user chooses to sync the code with an existing bucket, the script uses aws s3 sync to upload the built React app to the S3 bucket.
6. Creating a New Bucket: If the specified bucket doesn't exist, the script creates a new S3 bucket with the provided name and region using aws s3api create-bucket.
7. Set the Bucket Policy: A bucket policy is defined to allow public read access (s3:GetObject) for all objects (/*) in the specified bucket.
8. Create the S3 Bucket: The script creates an S3 bucket with the provided name and region using the AWS CLI.
9. Enable Static Website Hosting: Static website hosting is enabled for the bucket, and index.html is set as the index document.
10. Disable "Block All Public Access": The "Block all public access" setting is disabled to allow public access to the bucket.
11. Set the Bucket Policy: The previously defined bucket policy is applied to the bucket, granting public read access.
12. Upload the Build Files: The built React app files are uploaded to the S3 bucket using the aws s3 sync command.
13. Print the Deployed App URL: The script prints the URL of the deployed React app, which is accessible publicly.
14. Open the Deployed App: Finally, the script attempts to open the deployed app in the default browser based on the user's operating system (macOS or Windows).

Usage
To use the script, follow these steps:

1. Save the script to a file (e.g., deploy-react-app.sh).
2. Make the script executable by running chmod +x deploy-react-app.sh.
3. Run the script with ./deploy-react-app.sh.
4. Enter a unique bucket name when prompted.
5. Wait for the script to complete the deployment process.
6. Access your deployed React app at the provided URL.

Please find the github link below:-
https://github.com/akki907/aws_learning/blob/main/scripts/static-website-s3-deploy.sh

**Conclusion**

Automating deployment processes can significantly improve the efficiency and reliability of your development workflow. With the provided Bash script, you can easily deploy your React app to an AWS S3 bucket, making it publicly accessible as a static website. Feel free to modify the script to suit your specific needs or integrate it into your existing deployment pipeline.
Remember, automation is a powerful tool that can save you time, reduce errors, and ensure consistent deployments. By leveraging scripts like this, you can focus more on writing code and less on the deployment process itself.