Laravel

How to Backup Laravel Files and Database using AWS

February 13, 2018

author:

How to Backup Laravel Files and Database using AWS

If we backup in Amazon S3, an intruder can get access to its KEY and SECRET as they would be stored in the application itself. This way, the hacker can also get hold of Amazon account and delete backups from S3 bucket.

We talked at length about backups in general and backups in Laravel in the last post. There, we also used a third party package called laravel-backup to backup Laravel applications.

Though it worked as expected, it has some glitches. In case the application gets hacked, the hacker would also get access to the backup zips which discrete the purpose of backup altogether. Thus while taking a backup in Amazon S3, we will try and take care of this problem in mind.

Also, laravel-backup package needs to clean old backups as per settings in the config file, so it needs access to Delete Action on IAM user. So to save the backup from intruders, we can clean the action from Laravel application and create a fresh Lambda function to handle that.

And later, remove Delete action from IAM Policy which is associated with respective AWS user. Thus anyone having access to our AWS account, cannot delete backup files.

# Backup Setup

As discussed, we will use laravel-backup package by spatie. We used the same package in the last section as well, so hope you are familiar with it. Let us not waste much time there and get done with the setup:

Install Package:

composer require spatie/laravel-backup

Remember, we don’t need to register the service provider for 5.5+ Laravel versions. So let us publish the file:

php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"

This sets up the backup.php file within config directory of the application. Since we want to use s3, let us overwrite some rules in this file:

# backup.php
<?php

return [

    'backup' => [
        ...
        'destination' => [
            ...
            'disks' => [
                's3',
            ],
        ],
    ],
    ...
    'monitorBackups' => [
        [
            'name' => env('APP_URL'),
            'disks' => ['s3'],
            ...
        ],
       ...
    ],
    ...
];

# AWS Setup – Install Flysystem Package

Laravel manages system disks with a flysystem package. We need to fetch s3 specific drivers so that we can use s3 as a disk.

So let us first install the flysystem package:

composer require league/flysystem-aws-s3-v3

This command automatically generates filesystems.php file in the config directory. Since flysystem stores s3 related credentials, its recommended to store them in the .env file, thus let us configure them:

# .env
...
S3_BUCKET=[YOUR-S3-BUCKET-NAME]
S3_KEY=[YOUR-S3-KEY]
S3_SECRET=[YOUR-S3-SECRET]
S3_REGION=[YOUR-S3-REGION]

Let us now utilize the above keys in flysystem:

#config/flysystems.php
  ...
  's3' => [
      'driver' => 's3',
      'key'    => env('S3_KEY'),
      'secret' => env('S3_SECRET'),
      'region' => env('S3_REGION'),
      'bucket' => env('S3_BUCKET'),
  ],
  ...

# AWS S3 Bucket Setup

First of all, sign in the Management Console and click on S3 section. You may see your active buckets. You can also create a new Bucket by clicking on the Create bucket button.

Working with Amazon S3 for Laravel Backup

In the popped-up model, fill in the bucket name and select the specific region.

Create bucket in Amazon S3 for Laravel Backup

This creates a fresh bucket successfully.

# IAM User Setup

Next, in AWS console, go to IAM (Identity and Access Management) section, from the left sidebar, select Users tab or visit https://console.aws.amazon.com/iam/home. When it opens a list of active IAM users, click on Create New Users and add a new username.

Create IAM user in Amazon S3 for Laravel Backup

This will create a new user and show us an option to view or download the keys. On clicking Show User Security Credentials, it will let you see key ID and secret.

IAM Key ID and Secret in Amazon S3

When you close this page, you can track that the new user is added to the list. Click on the newly created user.

Add Permissions to IAM user in Amazon S3 for Laravel Backup

In the Permissions tab, click on Add inline policy, it may have Visual editor tab open. But we will use JSON option, so click on JSON tab and configure as:
Add Permission in JSON format for Amazon S3 IAM User for Laravel Backup

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1491223906000",
      "Effect": "Allow",
      "Action": [
          "s3:*"
      ],
      "Resource": [
          "arn:aws:s3:::hashvelblog-backup",
          "arn:aws:s3:::hashvelblog-backup/*"
      ]
    }
  ]
}

Note that AWS resource name must be a unique name which is the name of the bucket we created earlier. Go through the next steps in the console, and once it’s validated and applied, the policy will be generated and mapped with the specific IAM user.

# Take Backup

To take backup using laravel-backup package, run:

php artisan backup:run
Run Laravel Backup Command

Once it completes successfully, we can go to AWS console and in our bucket to confirm the backup zip:
Laravel Backup Zip in Amazon S3

Hence, everything works fine.

# Automate Backups

We already discussed taking automated backups in the last post so that you can refer that.

Conclusion:

All in all, it was an excellent session to backup Laravel projects. Taking backups on AWS can be tricky if you don’t know the correct workflow. Hope this tutorial helped you get an overall idea of that workflow.

QUESTIONS & COMMENTS:

Thank you for reading.  Hope you were able to backup your laravel applications with this step-by-by guide.. If you have any questions or suggestions, please share them in the comment section below.

Leave a comment

Your email address will not be published. Required fields are marked *