Trip Trip - 7 months ago 30
Ruby Question

How do you rename a folder in a bucket on S3?

As simple as it sounds, it seems like an extraordinarily complicated task.


If you're using the aws-s3 gem, the following code will rename folder OLD_FOLDER_NAME in bucket BUCKET_NAME to NEW_FOLDER_NAME:

bsize = OLD_FOLDER_NAME.size
bucket = AWS::S3::Bucket.find(BUCKET_NAME)
bucket.objects({:prefix=>OLD_FOLDER_NAME}).each do |o|
  AWS::S3::S3Object.rename(o.key, NEW_FOLDER_NAME + o.key[bsize..-1], BUCKET_NAME)

That's it. Folders aren't real objects, so all you have to do is rename all the objects that end up in that specific path to the new path. The virtual folder will be renamed as a result.