7

I'm able to delete individual files within a "Folder" on Amazon S3 using the following:

s3 = AWS::S3.new(:access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_ACCESS_KEY'])
folder_path = 'uploads/'[email protected]_filename
s3.buckets[ENV['AWS_BUCKET']].objects.with_prefix(folder_path).delete_all

but this leaves an empty folder. How can I just delete the folder entirely (folder_path)?

3 Answers 3

22

This is an old question, but you can do this for aws-sdk 2.0>

s3 = Aws::S3::Resource.new
folder = 'path/to/the/folder'
objects = s3.bucket(ENV['S3_BUCKET_NAME']).objects({prefix: folder})
objects.batch_delete!

delete was depreciated

Hope this helps!

2
  • 1
    This should be an accepted answer. Thanks @Jeremie , saved some time for me. Commented Aug 7, 2017 at 23:33
  • Yep, this is the proper way to do it.
    – Nuno Silva
    Commented Mar 3, 2018 at 18:11
6

Everything on S3 is an object you can manipulate by its "key". If you just grab it you can call delete on it:

s3.buckets[ENV['AWS_BUCKET']].objects["name of the folder"].delete
5
  • thanks for your help, but this doesn't seem to be working for me. I tried passing in both the name of the folder ("test") and the path to the folder within the bucket ("uploads/test"), but neither worked. Commented Jan 30, 2014 at 20:54
  • I don't get an error when I try running the code; it just doesn't do anything. Commented Jan 30, 2014 at 20:59
  • Did you try after delete_all object inside it? Commented Jan 30, 2014 at 21:01
  • yes, I can delete all objects inside the folder, just not the folder itself (as explained in the original post) Commented Jan 30, 2014 at 21:02
  • 1
    my mistake, it looks like the code I had posted originally was actually deleting the folder! The s3 console just wasn't refreshing. Commented Jan 30, 2014 at 21:48
1

You must delete all files in folder, after you can removed folder.

1
  • No need for that. See @Jeremie answer.
    – Nuno Silva
    Commented Mar 3, 2018 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.