Skip to content

Instantly share code, notes, and snippets.

@swombat
Created July 24, 2025 09:19
Show Gist options
  • Save swombat/1a716dd36629def549db0b9986827341 to your computer and use it in GitHub Desktop.
Save swombat/1a716dd36629def549db0b9986827341 to your computer and use it in GitHub Desktop.
Download backup from AWS and restore
namespace :db_backup do
desc "Download the latest database backup from AWS S3"
task download: :environment do
require 'aws-sdk-s3'
bucket_name = "<your-bucket>"
download_path = Rails.root.join('db', 'backups')
FileUtils.mkdir_p(download_path)
s3_client = Aws::S3::Client.new(region: 'eu-north-1')
bucket = Aws::S3::Resource.new(client: s3_client).bucket(bucket_name)
# Assuming backups are stored with a timestamp or identifiable pattern
latest_backup = bucket.objects(prefix: '').collect(&:key).sort.last
if latest_backup
puts "Downloading #{latest_backup}..."
obj = s3_client.get_object({ bucket: bucket_name, key: latest_backup }, target: "#{download_path}/#{File.basename(latest_backup)}")
puts "Downloaded to #{download_path}/#{File.basename(latest_backup)}"
else
puts "No backup found."
end
end
desc "Restore the latest downloaded database backup"
task restore: :environment do
download_path = Rails.root.join('db', 'backups')
latest_backup = Dir["#{download_path}/*.tgz"].max_by { |f| File.mtime(f) }
if latest_backup
# Extract the .tgz file
extracted_path = "#{download_path}/extracted"
FileUtils.mkdir_p(extracted_path)
system("tar -xzf #{latest_backup} -C #{extracted_path}")
# Assuming the database file is the only file in the extracted folder
db_file = Dir["#{extracted_path}/backup/*"].first
if db_file
db_config = Rails.configuration.database_configuration[Rails.env]
username = db_config["username"]
dbname = db_config["database"]
host = db_config["host"] || 'localhost'
puts "Restoring database from #{db_file}..."
puts "> pg_restore --verbose --clean --no-acl --no-owner -h #{host} -d #{dbname} #{db_file}"
system("pg_restore --verbose --clean --no-acl --no-owner -h #{host} -d #{dbname} #{db_file}")
puts "Database restored from #{db_file}"
# Clean up extracted files
FileUtils.rm_rf(extracted_path)
puts "Removed extracted files"
User.all.each do |user|
if user.update_column(:encrypted_password, user.send(:password_digest, 'password'))
puts "Password for user #{user.id} (#{user.email}) set to 'password'"
else
puts "Failed to set password for user #{user.id} (#{user.email})"
end
end
else
puts "No database file found in the extracted archive."
end
else
puts "No backup archive found to restore."
end
end
desc "Download and restore the latest database backup"
task download_and_restore: [:download, :restore] do
if Rails.env.production?
raise "This task cannot be run in the production environment!"
end
puts "Download and restore completed."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment