Rename an object in S3 using Ruby

I want to rename an element in s3 using Ruby sdk. How to do it?

I tried:

require 'aws-sdk'
s3 = AWS.config(
        :region => 'region',
        :access_key_id => 'key',
        :secret_access_key => 'key'
)

b = AWS::S3::Bucket.new(client: s3, name: 'taxalli')


    b.objects.each do |obj|
       obj.rename_to('imports/files/' + line.split(' ').last.split('/').last)
      end

But I don’t see anything in the new sdk for relocation or renaming.

+4
source share
3 answers

There is no thing like renaming to the Amazon S3 SDK. Basically, what you need to do is copy the object and then delete the old one.

    require 'aws-sdk'
    require 'open-uri'


    creds = Aws::SharedCredentials.new(profile_name: 'my_profile')

    s3 = Aws::S3::Client.new( region: 'us-east-1',
                              credentials: creds)



    s3.copy_object(bucket: "my_bucket",
                   copy_source: URI::encode("my_bucket/MyBookName.pdf"),
                   key: "my_new_book_name.pdf")

    s3.delete_object(bucket: "my_bucket",
                     key: "MyBookName.pdf")
+3
source

Source: https://habr.com/ru/post/1598975/


All Articles