REST APIでS3からオブジェクトを取得する

やりたいことがシンプルなわりにサンプルがほとんど見つからなかったので、メモしておきます。

require 'base64'
require 'net/http'
require 'openssl'
require 'time'

Net::HTTP.version_1_2

def aws_sign(secret_access_key_id, date, bucket, path)
  string_to_sign = "GET\n\n\n#{date}\n/#{bucket}#{path}"
  digest = OpenSSL::HMAC.digest(OpenSSL::Digest::SHA1.new, secret_access_key_id, string_to_sign)
  Base64.encode64(digest).gsub("\n", '')
end
  
def get(bucket, path, access_key_id, secret_access_key_id)
  host = "#{bucket}.s3.amazonaws.com"
  date = Time.now.rfc2822
  signature = aws_sign(secret_access_key_id, date, bucket, path)

  header = {
    'Host' => host,
    'Date' => date,
    'Authorization' => "AWS #{access_key_id}:#{signature}"
  }

  content = nil

  Net::HTTP.start(host, 80) do |http|
    content = http.get(path, header).body
  end

  return content
end

BucketName = 'my_bucket'
Path = '/path/to/example.txt'
AWSAccessKeyId = '<MyAWSAccessKeyId>'
AWSSecretAccessKey = '<MyAWSSecretAccessKey>'

content = get(BucketName, Path, AWSAccessKeyId, AWSSecretAccessKey)
puts content