Skip to content

Instantly share code, notes, and snippets.

@mrmarcondes
Last active December 11, 2015 18:03
Show Gist options
  • Save mrmarcondes/ee7770fb4d4f02694230 to your computer and use it in GitHub Desktop.
Save mrmarcondes/ee7770fb4d4f02694230 to your computer and use it in GitHub Desktop.
require 'aws-sdk'
# Copy an AWS S3 object from one bucket to another
class CopyObjectFromOneBucketToAnotherService
attr_reader :logger, :object_name, :object_to_copy, :destination_bucket
attr_accessor :debug
def initialize(options = {})
create_logger(STDOUT)
Aws.config.update(
region: options[:region],
credentials: Aws::Credentials.new(options[:access_key_id],
options[:secret_access_Key]))
end
def copy!(source_bucket, destination_bucket, object, options = {})
set_aws_objects source_bucket, destination_bucket, object
proceed options
end
def copy(source_bucket, destination_bucket, object, options = {})
set_aws_objects source_bucket, destination_bucket, object
proceed options unless @destination_bucket.object(object).exists?
end
private
def set_aws_objects(source_bucket, destination_bucket, object)
@source_bucket = Aws::S3::Bucket.new(source_bucket)
@destination_bucket = Aws::S3::Bucket.new(destination_bucket)
@object_name = object
@object_to_copy = @source_bucket.object(@object_name)
end
def proceed(options)
if @object_to_copy.exists?
logger.info "Copying #{@source_bucket.name}/#{@object_name}"
@object_to_copy.copy_to("#{@destination_bucket.name}/#{@object_name}", options)
logger.info "Copied to #{@destination_bucket.name}/#{@object_name}"
return
end
logger.info "Not found #{@source_bucket.name}/#{@object_name}"
end
def create_logger(output)
@logger = Logger.new(output).tap do |l|
l.level = Logger::INFO
end
end
end
=begin
Sample:
service = CopyObjectFromOneBucketToAnotherService.new(access_key_id: 'access-key',
secret_access_Key: 'secret-access-key',
region: 'region')
service.copy!('source-bucket', 'destination-bucket', 'object', acl: 'public-read')
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment