読者です 読者をやめる 読者になる 読者になる

REST APIでS3のオブジェクトリストを取得する

require 'rubygems'
require 'base64'
require 'cgi'
require 'net/http'
require 'nokogiri'
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 list(bucket, prefix, access_key_id, secret_access_key_id)
  host = "#{bucket}.s3.amazonaws.com"
  path = '/?prefix=' + CGI.escape(prefix)
  date = Time.now.rfc2822
  signature = aws_sign(secret_access_key_id, date, bucket, '/')

  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 Nokogiri::HTML(content)
end

BucketName = 'my_bucket'
Prefix = 'foo/bar/zoo'
AWSAccessKeyId = '<MyAWSAccessKeyID>'
AWSSecretAccessKey = '<MyAWSSecretAccessKey>'

doc = list(BucketName, Prefix, AWSAccessKeyId, AWSSecretAccessKey)

doc.css('contents key').each do |key|
  puts key.content
end