78
82

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AWS SDK for Ruby(V2)を利用して、Amazon S3を操作する

Posted at

しばらく触らないうちにV2とか出てたりしたので、基本操作のおさらい。

Gemでインストール

$ gem install aws-sdk-core
$ gem list aws-sdk-core
*** LOCAL GEMS ***
aws-sdk-core (2.0.3)

Credentialsの設定

~/.aws/credentials
[default]
aws_access_key_id = your_access_key_id
aws_secret_access_key = your_secret_access_key

バケットの一覧表示

aws-sdk-ruby-s3.rb
require "aws-sdk-core"

Aws.config[:region] = 'ap-northeast-1'
s3 = Aws::S3::Client.new

resp = s3.list_buckets
puts resp.buckets.map(&:name)

バケットの作成

s3.create_bucket(bucket: "BucketName")

バケットの削除

s3.delete_bucket(bucket: "BucketName")

オブジェクトの一覧表示

resp = s3.list_objects(bucket: "BucketName")
resp.contents.each do |object|
	puts "#{object.key}"
end

オブジェクトの削除

s3.delete_object(
    bucket: "BucketName",
    key: "sample.jpg"
)

ファイルのアップロード

file_open = File.open("sample.jpg")
file_name = File.basename("sample.jpg")

s3.put_object(
	bucket: "BucketName",
	body: file_open,
	key: file_name
)

ファイルのダウンロード

File.open("sample.jpg", "w") do |file|
    s3.get_object(bucket: "BucketName", key: "sample.jpg") do |chunk|
        file.write(chunk)
    end
end

参考リンク

78
82
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
78
82

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?