March 17, 2021 / Eternal Team
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
Step 1: Create an S3 bucket with a name:
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://
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.