Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bouzuya
Last active May 12, 2020 01:07
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bouzuya/6559140 to your computer and use it in GitHub Desktop.
Save bouzuya/6559140 to your computer and use it in GitHub Desktop.
AWS SDK for Ruby で S3 を操作する
require 'rubygems'
require 'bundler/setup'
require 'aws-sdk'
# NOTE: require ENV[...]
# export AWS_ACCESS_KEY_ID='...'
# export AWS_SECRET_ACCESS_KEY='...'
# export AWS_REGION='ap-northeast-1'
s3 = AWS::S3.new
# bucketを作成
bucket_name = 'bouzuya2'
s3.buckets.create bucket_name unless s3.buckets[bucket_name].exists?
# そのIAMユーザーから見えるすべてのbucketを表示
s3.buckets.each do |bucket|
puts bucket.name
end
bucket = s3.buckets[bucket_name]
file_path = 'README.md'
File.open(file_path, 'w') do |f|
f.write 'Hello, S3!'
end
# bucketにobjectをアップロード
object_name = file_path
object = bucket.objects[object_name]
object.write(file: file_path) unless object.exists?
# 複数ファイル
object_name = file_path + '.bk'
object = bucket.objects[object_name]
object.write(file: file_path) unless object.exists?
# folderもつくれる
object_name = 'dir1/' + file_path
object = bucket.objects[object_name]
object.write(file: file_path) unless object.exists?
# 複数ディレクトリ
object_name = 'dir2/' + file_path
object = bucket.objects[object_name]
object.write(file: file_path) unless object.exists?
# bucketのobject一覧を確認
bucket.objects.each do |object|
puts object.key
# puts object.public_url
end
# ファイルを読み取る
object_name = file_path
object = bucket.objects[object_name]
puts object.read
# 大きいファイルを読み取る
object_name = file_path
object = bucket.objects[object_name]
object.read do |chunk|
puts chunk
end
# ファイルを削除する
bucket.objects.each do |object|
object.delete
end
# bucketを削除する
bucket.delete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment