Skip to content

Instantly share code, notes, and snippets.

@dingman
Created February 13, 2020 21:32
Show Gist options
  • Save dingman/177d25471fc4fcca0ac8ed2c3939de15 to your computer and use it in GitHub Desktop.
Save dingman/177d25471fc4fcca0ac8ed2c3939de15 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# WP-CLI Back up Script to Amazon S3
# Source: https://www.jonathan.vc
# Author: Jonathan Dingman
# Adapted from Mike at WP Bullet
#define local path for backups
BACKUPPATH=/tmp/backups
#path to WordPress installations
SITESBASE=/var/www
#S3 bucket
S3DIR="s3://yourbucketname"
#date prefix
DATEFORM=$(date +"%Y-%m-%d")
#Days to retain
DAYSKEEP=7
# Alternate DB Host - useful if you have a high availability setup and want to leverage a read-only user, instead of the Writer.
ALTDBHOST="yourdatabase.rds.amazonaws.com" # completely optional, in my use-case, it made sense.
#calculate days as filename prefix
DAYSKEPT=$(date +"%Y-%m-%d" -d "-$DAYSKEEP days")
# Create array() of domains listed in $SITESBASE
SITELIST=()
for DIR in "$SITESBASE"/*/ ; do
DIR2=${DIR%/} # Remove the trailing /
DIR3=${DIR2##*/} # Remove everything up to, and including, the last /
if [[ ${DIR3} = *"."* ]]; then # Only add strings that have a period in them (ex: domain names)
SITELIST+=( "$DIR3" )
fi
done
#make sure the backup folder exists
mkdir -p "$BACKUPPATH"
#start the loop
for SITE in "${SITELIST[@]}"; do
cd "$SITESBASE/$SITE/htdocs" || exit
if [ ! -e "$BACKUPPATH/$SITE" ]; then
mkdir "$BACKUPPATH/$SITE"
fi
tar -czf "$BACKUPPATH/$SITE/$DATEFORM-$SITE.tar.gz" -C "$SITESBASE/$SITE" .
wp db export "$BACKUPPATH/$SITE/$DATEFORM-$SITE".sql \
--host="$ALTDBHOST" \
--path="$SITESBASE/$SITE/htdocs" \
--single-transaction \
--quick \
--lock-tables=false \
--allow-root \
--skip-themes \
--skip-plugins
< "$BACKUPPATH/$SITE/$DATEFORM-$SITE".sql gzip > "$BACKUPPATH/$SITE/$DATEFORM-$SITE".sql.gz
rm "$BACKUPPATH/$SITE/$DATEFORM-$SITE".sql
S3DIRUP="$S3DIR/$SITE/$DATE"
aws s3 mv "$BACKUPPATH/$SITE/$DATEFORM-$SITE".tar.gz "$S3DIRUP"
aws s3 mv "$BACKUPPATH/$SITE/$DATEFORM-$SITE".sql.gz "$S3DIRUP"
#delete old backups
S3REM="$S3DIR/"
aws s3 rm "$S3REM/$DAYSKEPT"
done
#if you want to delete all local backups
#rm -rf "${BACKUPPATH:?}/*"
#delete old backups locally over DAYSKEEP days old
# find "$BACKUPPATH" -type d -mtime +$DAYSKEEP -exec rm -rf {} \;
@PabloWestphalen
Copy link

Hot stuff bro, appreciate the share!

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