Amazon Simple Storage Service
Developer Guide (API Version 2006-03-01)

Copy an Object Using the AWS SDK for Ruby

The following tasks guide you through using the Ruby classes to copy an object in Amazon S3, from one bucket to another or to copy an object within the same bucket.

Copying Objects


Create an instance of the AWS::S3 class by providing your AWS credentials.


Execute either the AWS::S3::S3Object#copy_to or AWS::S3::S3Object#copy_from method. You need to provide the request information, such as source bucket name, source key name, destination bucket name, and destination key.

The following Ruby code sample demonstrates the preceding tasks using the #copy_to method to copy an object from one bucket to another.

Copy to clipboard
s3 = # Upload a file and set server-side encryption. bucket1 = s3.buckets[source_bucket] bucket2 = s3.buckets[target_bucket] obj1 = bucket1.objects[source_key] obj2 = bucket2.objects[target_key] obj1.copy_to(obj2)


The following Ruby script example makes a copy of an object using the #copy_from method. The copied object with a different key is saved in the same source bucket. For instructions about how to create and test a working sample, see Using the AWS SDK for Ruby - Version 2.

Copy to clipboard
#!/usr/bin/env ruby require 'rubygems' require 'aws-sdk' bucket_name = '*** Provide bucket name ***' source_key = '*** Provide source key ***' target_key = '*** Provide target key ***' # Get an instance of the S3 interface. s3 = # Copy the object. s3.buckets[bucket_name].objects[target_key].copy_from(source_key) puts "Copying file #{source_key} to #{target_key}."