# Using Amazon S3 to back up and restore data

> Set up Amazon S3 as an offsite backup destination for your hosting account and restore files from it.

Source: https://helpcenter.ruachost.com/cpanel/files/using-amazon-s3-to-back-up-and-restore-data-in-ruachost/

Ruachost allows you to configure **Amazon S3** as an offsite backup destination for your hosting account. This ensures your website files and databases are securely stored in the cloud and can be restored if needed.

## Why Use Amazon S3 for Backups?

- **Offsite protection**: Keeps your data safe even if your hosting server is compromised.
- **Scalability**: Store large amounts of data without worrying about local disk limits.
- **Automation**: Schedule backups to run automatically via cron jobs.
- **Reliability**: Benefit from Amazon’s highly available cloud infrastructure.

## Prerequisites

Before you begin, you’ll need:

- An **Amazon Web Services (AWS) account**.
- An **IAM user** with programmatic access enabled.
- The user’s **Access Key** and **Secret Key**.
- An **S3 bucket** created in your AWS account.

## Installing and Configuring `s3cmd`

`s3cmd` is a command-line tool that allows you to interact with Amazon S3.

1. **Log in to your Ruachost account via SSH.**
2. Create a Python virtual environment:

   ```bash
   cd ~
   virtualenv amazon
   source ~/amazon/bin/activate
   ```
3. Install `s3cmd:`

   ```bash
   pip install s3cmd python-magic
   ```
4. Make it executable:

   ```bash
   chmod +x ~/amazon/bin/s3cmd
   ```
5. Configure `s3cmd`:

   ```bash
   s3cmd --configure
   ```

   - Enter your **Access Key** and **Secret Key**.
   - Accept defaults for encryption and GPG.
   - Choose **Yes** for HTTPS.
   - Test credentials, you should see a **Success** message.

## Backing Up Data to Amazon S3

1. Ensure your virtual environment is active:

   ```bash
   source ~/amazon/bin/activate
   ```
2. Create a new bucket (replace `bucketname` with your own):

   ```bash
   s3cmd mb s3://bucketname
   ```
3. Verify the bucket:

   ```bash
   s3cmd ls
   ```
4. Set up a cron job to back up your site daily at 2:30 AM:

   ```bash
   30 2 * * * source /home/username/amazon/bin/activate; s3cmd sync --preserve --recursive /home/username/public_html s3://bucketname
   ```

   ```
   \
   Replace username with your Ruachost account username.
   ```

   - Use `sync` instead of `put` for efficiency (only new/changed files are uploaded).

## Restoring Data from Amazon S3

1. Activate your virtual environment:

   ```bash
   source ~/amazon/bin/activate
   ```
2. Restore files from your bucket:

   ```bash
   s3cmd get --recursive s3://bucketname/path /home/username/restore/
   ```

   - Replace `path` with the folder or file path in S3.
   - Replace `/home/username/restore/` with your desired destination.
