Phil-6
Phil-6

Reputation: 815

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.

Upvotes: 7

Views: 6383

Answers (3)

CeamKrier
CeamKrier

Reputation: 839

There is an alternative way to achieve this by using lifecycle settings in the bucket configuration:

enter image description here

Setting "Delete uploaded objects after" to 0 will empty the whole bucket the next day

Upvotes: 8

Phil-6
Phil-6

Reputation: 815

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

Upvotes: 1

Joel Wigton
Joel Wigton

Reputation: 812

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.

Upvotes: 22

Related Questions