• Trellis

Backing Up Trellis Sites to an S3 Bucket

Add backup shell script

Create site/scripts/backup-to-s3.sh with the following contents:

#!/bin/bash
eval $(cat ../.env | sed 's/^/export /')
export AWS_CONFIG_FILE="/home/web/.aws/config"
SITE="${DB_USER//_/.}"
ENVIRONMENT="$WP_ENV"
TIMESTAMP=`env TZ=America/Denver date +%Y-%m-%d-%H%M`
ARCHIVE_PATH=/tmp/$SITE-$ENVIRONMENT-$TIMESTAMP
ARCHIVE_FILENAME=$SITE-$ENVIRONMENT-$TIMESTAMP.tar.gz
mkdir -p $ARCHIVE_PATH &&
cd /srv/www/$SITE/current && wp db export $ARCHIVE_PATH/db.sql &&
rsync -kavzP --exclude web/wp/ --exclude web/wp-config.php /srv/www/$SITE/current/web $ARCHIVE_PATH &&
rsync -kavzP /srv/www/$SITE/shared/uploads $ARCHIVE_PATH/web/app &&
tar -C $ARCHIVE_PATH -czf /tmp/$ARCHIVE_FILENAME . &&
/usr/local/bin/aws s3 cp /tmp/$ARCHIVE_FILENAME s3://site-backups/$SITE/$ARCHIVE_FILENAME &&
rm -rf $ARCHIVE_PATH &&
rm /tmp/$ARCHIVE_FILENAME

Notes

  • Replace s3://site-backups with the name of an existing S3 bucket
  • Make sure the permissions for site/scripts/backup-to-s3.sh allow it to be executed (chmod +x backup-to-s3.sh)

Trellis modifications

Add to wordpress-setup/tasks/main.yml:

- name: Setup nightly cron for S3 backup
  cron:
    name: "{{ item.key }} nightly S3 backup"
    minute: "0"
    hour: "12"
    user: "{{ web_user }}"
    job: "cd {{ www_root }}/{{ item.key }}/{{ item.value.current_path | default('current') }}/scripts && ./backup-to-s3.sh > /dev/null 2>&1"
    cron_file: "backup-nightly-{{ item.key | replace('.', '_') }}"
  with_dict: "{{ wordpress_sites }}"
  when: env != 'development'

Add to trellis/requirements.yml:

- name: aws-cli
  src: https://github.com/dstil/ansible-aws-cli
  version: 5c1c14d9b0e6264605bd475c86d4ea67e7d5896f

And then run ansible-galaxy install -r requirements.yml.

Add to trellis/server.yml:

    - { role: aws-cli, tags: [aws-cli] }

Add to trellis/group_vars/all/vault.yml:

vault_aws_access_key_id: xxxxxxx
vault_aws_secret_access_key: "xxxxxxx"

Read the discussion on Roots Discourse

Ready to checkout?