Created
August 13, 2025 12:56
-
-
Save andrepiske/81da74c788e13638d1a801dd8f199315 to your computer and use it in GitHub Desktop.
permanent_delete_s3_versioned.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # params: | |
| # - bucket: String, the name of the bucket | |
| # - key: String, the file name in S3 ("key" in S3 naming scheme) | |
| def permanently_delete_key(s3_client, bucket, key) | |
| # One can get the s3 client from the ActiveStorage instance, | |
| # or if not using ActiveStorage, just instantiate one with: | |
| # s3_client = Aws::S3::Client.new | |
| obj_versions_resp = s3_client.list_object_versions(bucket:, prefix: key) | |
| obj_versions = obj_versions_resp.versions.select{ |x| x.key == key } | |
| delete_markers = obj_versions_resp.delete_markers.select{ |x| x.key == key } | |
| objects_to_delete = (delete_markers + obj_versions).map do |entry| | |
| { key: entry.key, version_id: entry.version_id } | |
| end | |
| rs = s3_client.delete_objects({ | |
| bucket:, | |
| delete: { | |
| objects: objects_to_delete, | |
| quiet: false } | |
| }) | |
| if rs.errors.length > 0 | |
| # TODO: should retry from the beginning or something, because this means not all versions have been deleted | |
| end | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment