Easy Way To Backup SnipeIt To AWS S3

Ragav G

1 min read

SnipeIt? What is that? SnipeIt is an open-source asset management system using which you can manage your organization’s assets. You can get more detail on that https://snipeitapp.com/.

We came across a scenario where we need to backup the asset management (which uses SnipeIt) daily and upload it to the S3 bucket.

I can’t do this task daily, so yeah let’s get this done using a simple shell script.

  1. Initialize a log file
    LOGFILE="/var/log/snipeit-backup.log"
    echo "**************START*************************" >> $LOGFILE
    
  2. Navigate to the asset management directory and initialize the snipeit backup command
    php artisan snipeit:backup
    cd /var/www/snipeit/
    php artisan snipeit:backup >> $LOGFILE
    
  3. Now we need to figure out which is the latest backup in the backup folder
    Here is the command to find the latest modified file in the specific folder.
    cd /var/www/snipeit/storage/app/backups
    Filename=$(ls -Art | tail -n 1)
    
  4. Upload the latest backup file to S3 bucket
    echo 'Backup uploading to S3 bucket'  >> $LOGFILE
    /snap/bin/aws s3 cp $Filename s3://BUCKET_NAME/FOLDER_NAME/ >> $LOGFILE
    
  5. Delete all the backups older than 3 days
    echo 'Deleting backup older than 3 days'  >> $LOGFILE
    find /var/www/snipeit/storage/app/backups -type f -name '*.zip' -mtime +3 -exec rm {} \;
    
  6. Now lets notify that everything went well using email
    SENDGRID_API_KEY="INSERT_YOUR_KEY_HERE"
    BAK_DATETIME=`date +%F-%H:%M`
    SUBJECT="Asset Mangement Backup was succcessful at: ${BAK_DATETIME}"
    REQUEST_DATA='{"personalizations": [{ 
         "to": [{ "email": "foo@foo.com" }],
         "subject": "'"$SUBJECT"'"
      }],
      "from": {
          "email": "foo@foo.com",
          "name": "foo.com" 
      },
      "content": [{
          "type": "text/plain",
          "value": "This is an automated message to inform that Asset backup ('"$Filename"') completed successfully to S3 bucket."
      }]
    }';
    
    curl -X "POST" "https://api.sendgrid.com/v3/mail/send" \
     -H "Authorization: Bearer $SENDGRID_API_KEY" \
     -H "Content-Type: application/json" \
     -d "$REQUEST_DATA"
    
    echo "Sent email notification via sendgrid" >> $LOGFILE
    echo "***************END***************************" >> $LOGFILE
    
  7. Now for the final step set the cron at 12 A.M. daily to run this shell script.
    Here is the cron location /etc/crontab. Add this code to the crontab:
    0 0    * * *   root    /var/www/snipeit/snipeit-backup.sh
    

Here is the full code snippet for reference:

Hope this will be useful to you. 🙂 Feel free to comment here if you have any questions.

Related posts:

Leave a Reply

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