3

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.

Phil-6
  • 552
  • 6
  • 16
  • 1
    I've never used this but it seems you can use the `aws cli` - https://developers.cloudflare.com/r2/examples/aws-cli/ - so maybe `aws s3 rm --endpoint-url https://.r2.cloudflarestorage.com --recursive` will delete everything? Be careful, I didn't test it. – Juan Fontes Sep 28 '22 at 07:40

2 Answers2

11

Thanks to Juan Fontes' comment above, I tried this out and the following worked.

aws s3 rm s3://<bucket-name> --endpoint-url https://<cloudflare-id>.r2.cloudflarestorage.com --recursive --dryrun

After it's working for you, rerun without the --dryrun flag.

Don't forget to configure the AWS CLI first.

Joel Wigton
  • 642
  • 6
  • 15
1

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
Phil-6
  • 552
  • 6
  • 16