2
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

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

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

環境

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にオブジェクトの名前の一覧が取得される。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
2
Help us understand the problem. What are the problem?