Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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

環境

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

b_a_a_d_o
怠惰で短気で傲慢なえんじにあ
https://www.gowest1.com/
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