Search code examples
amazon-s3cloudflarecloudflare-r2

Cloudflare R2 - Delete all objects from bucket


Is there an easy way to delete all objects from a Cloudflare R2 bucket?

This isn't something I'd want to do in production, but something that I want to do while testing in development. I'd love to be able to select more than 25 objects at a time from the dashboard or delete all objects from a CLI.


Solution

  • I found a way to do this from the Rails Console using ActiveStorage

    ActiveStorage::Blob.services.fetch(:cloudflare_user_pictures).bucket.objects.batch_delete!
    

    Where :cloudflare_user_pictures is the name of your service.

    I run this at the end of my test suite to remove all pictures from the test buckets on cloudflare:

    Minitest.after_run do
      ActiveStorage::Blob.services.fetch(:cloudflare_user_pictures).bucket.objects.batch_delete!
      ActiveStorage::Blob.services.fetch(:cloudflare_chat_message_attachments).bucket.objects.batch_delete!
    end