Skip to content

Instantly share code, notes, and snippets.

@agaoglu
Created June 24, 2014 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agaoglu/69de99b3407fd7e991fc to your computer and use it in GitHub Desktop.
Save agaoglu/69de99b3407fd7e991fc to your computer and use it in GitHub Desktop.
Backup mongodb directly to S3 (without using local disk). Requires http://s3tools.org/s3cmd.
#!/bin/bash
#########
# Copyright 2014 Erdem Agaoglu
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##########
# NOTES: #
##########
#
# Requires http://s3tools.org/s3cmd. Run `s3cmd --configure` to define
# your AWS credentials if this is the first time you use s3cmd.
#
# Configure your mongodb installation and s3 bucket in the variables.
#
# Some bug in s3cmd multipart-uploads causes outputs like:
#
# File '-' stored as 's3://backups/prefix/collection.bson.gz'
# (0 bytes in 1.5 seconds, -1.00 B/s) [1 of 1]
#
# Problem seems cosmetic.
#
# Stored object's Etag is not the file's md5sum. Some clients (s3cmd
# included) will issue a warning when you get the file.
#
##########
DATE=`date +%Y%m%d%H%M`
MONGOHOST=mongohost.example.com
MONGODB=mongodbname
S3CMDCONFIG=/home/user/.s3cfg
S3BUCKET=backups
S3PREFIX=mongohost/${MONGODB}/${DATE}/
MONGOCOLLS=`mongo ${MONGOHOST}/${MONGODB} --eval 'rs.slaveOk(); db.getCollectionNames()' |tail -1 |sed 's/,/ /g'`
LOGFILE=/var/log/backups/${MONGODB}.backup.${DATE}.log
echo --- `date +%Y%m%d%H%M%S` START | tee -a $LOGFILE
for coll in $MONGOCOLLS
do
s3pos=s3://${S3BUCKET}/${S3PREFIX}${coll}.bson.gz
echo --- `date +%Y%m%d%H%M%S` DUMPING $coll to $s3pos | tee -a $LOGFILE
mongodump --host $MONGOHOST --db $MONGODB --collection $coll --out - |gzip -c |/usr/local/bin/s3cmd --config $S3CMDCONFIG put - $s3pos 2>&1| tee -a $LOGFILE
done
echo --- `date +%Y%m%d%H%M%S` END | tee -a $LOGFILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment