Skip to content

Instantly share code, notes, and snippets.

@lee-dohm
Forked from david-vo/push_db_to_s3
Last active December 22, 2015 20:39
Show Gist options
  • Save lee-dohm/6527737 to your computer and use it in GitHub Desktop.
Save lee-dohm/6527737 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# Script to backup the Discourse postgres db and upload it to Amazon S3
require 'rubygems'
require 'yaml'
require 'fog'
require 'time'
require 'date'
require 'fileutils'
#Add date/time enhancements
#Inspired by the activesupport gem: http://rubydoc.info/gems/activesupport/Time
class Fixnum
def seconds
self
end
alias_method :second, :seconds
def minutes
seconds * 60
end
alias_method :minute, :minutes
def hours
minutes * 60
end
alias_method :hour, :hours
def days
hours * 24
end
alias_method :day, :days
def weeks
days * 7
end
alias_method :week, :weeks
def months
days * 30
end
alias_method :month, :months
def years
days * 365
end
alias_method :year, :years
def ago
Time.now - self
end
def from_now
Time.now + self
end
end
bucket = "qa-discourse-backup"
file_date = Time.now.strftime('%Y%m%d-%H:%M:%S')
backupfile = "discourse-#{file_date}.dump"
#Create a backup of the Discourse database with temp name
#Todo add current timestamp later
Fileutils.cd('/home/discourse')
puts "Creating backup file - #{backupfile}"
puts
puts
system("pg_dump discourse_prod > #{backupfile}")
# use yaml to open the .fog file and extract the credentials we need
creds = YAML::load(File.read('.fog'))
aws_access_key_id_test = creds[:default][:aws_access_key_id_test]
aws_secret_access_key_test = creds[:default][:aws_secret_access_key_test]
# create a connection
connection = Fog::Storage.new({
:provider => 'AWS',
:aws_access_key_id => aws_access_key_id_test,
:aws_secret_access_key => aws_secret_access_key_test
})
directory = connection.directories.create(
:key => bucket,
:public => true
)
puts "Uploading #{backupfile}"
puts
puts "You can reach it by visiting:"
puts "https://s3.amazonaws.com/#{bucket}/#{backupfile}"
puts
puts
file = directory.files.create(
:key => backupfile,
:body => File.open("/home/discourse/#{backupfile}"),
:public => true
)
puts "Starting cleanup ..."
puts
puts "Deleting local backup file - #{backupfile}"
File.delete(backupfile)
puts
puts "Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment