Backup WordPress site to AWS S3 bucket

Backup WordPress site to AWS S3 bucket

March 17, 2021 / Nirav S

Back up your WordPress website to Amazon Web Services (AWS) S3 Bucket

In this blog, we are going to explain how to take a backup of WordPress site code and data onto an S3 bucket.

Pre-requisites

  • AWS account
  • AWS CLI
  • SSH and DB Access to WordPress Server

Steps To Backup WordPress Site To AWS S3 Bucket

Step 1: Create an S3 bucket with a name: -backup.

Step 2: Create an IAM user with a name: wordpress-s3-backup-user and attach the following policy to this user.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:ListBucketMultipartUploads",
                "s3:AbortMultipartUpload",
                "s3:ListMultipartUploadParts"
            ],
            "Resource": [
                "arn:aws:s3:::-backup",
                "arn:aws:s3:::-backup/*"
            ],
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": ""
                }
            }
        }
    ]
}

Step 3: Create a Read-only MySQL DB user with SELECT permission on all WordPress DB tables.

To do so, connect to MySQL DB and execute the following commands:

CREATE USER ‘wordpress_backupuser’@’localhost’ IDENTIFIED BY ‘‘;

GRANT SELECT ON * . * TO ‘wordpress_backupuser’@’localhost’;

Step 4: SSH to the WordPress server and install AWS CLI. And also configure the CLI with credentials created in Step 2.

pip3 install aws cli –upgrade –user

touch test-aws-access.txt

aws s3 cp test-aws-access.txt s3://-backup

Step 5: Create the following S3 backup script with a name: wordpress-s3-backup.sh

# MySQL Dump
mysqldump --single-transaction -u wordpress_backupuser -p -h localhost  > /tmp/wordpress-dump.sql
# Zip wordpress code
rm -rf /tmp/wordpress-code.zip
zip -r /tmp/wordpress-code.zip /path/to/your/wordpress-root-dir
dy=`date --date="-1 day" '+%Y'`
dm=`date --date="-1 day" '+%m'`
dd=`date --date="-1 day" '+%d'`
# Copy to S3
/path/to/aws s3 cp /tmp/wordpress-dump.sql s3://-backup/$dy/$dm/$dd/db/
/path/to/aws s3 cp /tmp/wordpress-code.zip s3://-backup/$dy/$dm/$dd/code/

Step 6: Setup Cron Jobs to take backup periodically with the following Cron expression:

#crontab -e

# Executes backup script midnight of every day.
0 0 * * * /path/to/wordpress-s3-backup.sh

Step 7: And Set Up an S3 bucket lifecycle rule to delete older backup data. This will help you with S3 storage cost.

Talk to AWS Certified Consultant

    Let Us Talk About Your AWS Development Requirements

    Have queries about your AWS project ideas and concepts? Please drop in your project details to discuss with our AWS experts, professionals and consultants.

    • Swift Hiring and Onboarding
    • Experienced and Trained AWS Team
    • Quality Consulting and Programming
    Let’s Connect and Discuss Your Project