0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Fog::AWS で S3 の bucket にある全てのファイルを取得する

Posted at

やりたいこと

Fog::AWS を使って、S3 の特定の bucket にある全てのファイルを取得したい。

しかし Fog::AWS::Storage::Directory#filesFog::AWS::Storage::Files#all を使っても 1,000 件のファイルしか取得できない :cry:

s3 = Fog::Storage.new(provider: 'AWS', use_iam_profile: true)
directory = s3.directories.get('my-bucket-name')
files = directory.files
files.count
#=> 1000

files = directory.files.all
files.count
#=> 1000

ファイルが 1,000 件より多く存在する場合でも全てのファイルを取得したい。

方法

Fog::AWS::Storage::Files#allmarker を渡すことで続きのファイルを取得する。

def find_all_files_in(directory)
  Enumerator.new do |y|
    marker = nil
    
    loop do
      files = directory.files.all(marker: marker)
      break if files.none?
      
      files.each_with_index do |file, i|
        y << file
        # 最後の要素
        marker = file.key if i + 1 == files.size
      end
    end
  end
end

files = find_all_files_in(directory)
files = files.to_a
files.size #=> 5432

バージョン情報

Fog::AWS::VERSION
#=> "3.30.0"

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?