Skip to content

Instantly share code, notes, and snippets.

@larstobi
Created March 19, 2012 14:08
Show Gist options
  • Select an option

  • Save larstobi/2113552 to your computer and use it in GitHub Desktop.

Select an option

Save larstobi/2113552 to your computer and use it in GitHub Desktop.
Sync directory to Amazon S3
#!/usr/bin/env ruby
require 'rubygems'
require 'fog'
require 'digest/md5'
local_directory = 'bootstrap'
remote_directory = 'bootstrap'
bucket_name = 'mybucket'
provider = 'AWS'
region = 'eu-west-1'
key_id = 'mykey'
key_secret = 'mysecret'
src_dir = File.join(File.expand_path(File.dirname(__FILE__)), local_directory)
local_files = Dir.entries(src_dir).select do |filename|
filename unless filename == '.' or filename == '..'
end
connection = Fog::Storage.new({
:provider => provider,
:aws_access_key_id => key_id,
:aws_secret_access_key => key_secret,
:region => region
})
bucket = connection.directories.get(bucket_name)
local_files.each do |filename|
remote_filename = File.join remote_directory, filename
local_filename = File.join src_dir, filename
file = bucket.files.get(remote_filename)
if file.nil?
puts "Creating new remote file #{remote_filename}"
bucket.files.create(
:key => remote_filename,
:body => File.open(local_filename),
:public => true
)
else
local_md5 = Digest::MD5.hexdigest(File.read(local_filename))
unless local_md5 == file.etag
puts "Saving changed file #{remote_filename}"
file.body = File.open(local_filename)
file.acl = 'public-read'
file.save
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment