LoginSignup
3
2

More than 5 years have passed since last update.

RubyでAWS S3のオブジェクトの一覧を取得してみた

Last updated at Posted at 2018-07-01

某所で似たような記事を見かけたので、軽く書いてみた。

環境

Ruby 2.6.0-preview2
aws-sdk gem 3.0.1
irbからでもrbファイルでも。

コード

require "aws-sdk"

# 環境に応じて記載
S3_REGION = "us-west-2".freeze
S3_BUCKET_NAME = "bucket-name".freeze
S3_PREFIX = "directory-name/".freeze
AWS_ACCESS_KEY = "".freeze
AWS_SECRET_ACCESS_KEY = "".freeze

Aws.config.update(
  region: S3_REGION,
  credentials: Aws::Credentials.new(AWS_ACCESS_KEY, AWS_SECRET_ACCESS_KEY)
)
s3 = Aws::S3::Client.new

current_bucket_files = Set.new
options = { bucket: S3_BUCKET_NAME, prefix: S3_PREFIX, max_keys: 1000 }
loop do
  res = s3.list_objects_v2(options)
  current_bucket_files |= res.contents.map(&:key)
  options[:continuation_token] = res.next_continuation_token
  break unless options[:continuation_token]
end

current_bucket_filesにオブジェクトの名前の一覧が取得される。

3
2
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
3
2