rubyamazon-s3fog

How to copy all files in a folder on s3 using Fog in Ruby


How do I copy all the files present in an s3 directory(same prefix) to another directory in the same bucket using fog?

For eg: Copy all files with prefix <bucket>/foo/ to <bucket>/bar/


Solution

  • I don't think there is a direct way to do that per se, and that instead you would need to iterate over the appropriate files to do the move. I think it would look something like this:

    require 'rubygems'
    require 'fog'
    
    # create a connection
    connection = Fog::Storage.new({
      provider:             'AWS',
      aws_access_key_id:     YOUR_AWS_ACCESS_KEY_ID,
      aws_secret_access_key: YOUR_AWS_SECRET_ACCESS_KEY
    })
    
    directory = connection.directories.get(BUCKET, prefix: '/foo/')
    
    directory.files.each do |file|
      file.copy(BUCKET, "/bar/#{file.key.split('/').last}")
    end