如何使用Ruby AWS SDK v2创建指向特定版本对象的预签名链接?

时间:2016-06-08 22:49:49

标签: ruby amazon-web-services amazon-s3

我正在使用the Ruby AWS SDK (v2)将日志文件上传到版本化的S3存储桶。日志文件不公开,但我希望生成一个预定的日志链接,以便通过聊天集成在有限的时间内使用它。我想链接到特定版本,this answer可以通过S3控制台说明。

Aws::S3::Presigner上的文档显示了如何为未版本化的对象(或版本化对象的头版本)执行此操作,但不针对特定版本执行此操作。 #presigned_url的可能参数没有很好地记录,并且读取源看起来像参数只是传递给Seahorse::Client::Base#build_request,而不是特定于S3。

1 个答案:

答案 0 :(得分:0)

我想我终于解决了这个问题,尽管我仍然不确定我是否可以追踪整个代码路径。简而言之:您可以将options参数中的:version_id传递给presigned_url

#
# Uploads a log to S3 at the given key, returning a URL
# to the file that's good for one hour.
#
# @param [String] bucket
# @param [String] key
# @param [String] body of the log to be uploaded
# @param [Hash] options
# @return [String] public URL of uploaded log, valid for one hour
# @raise [Exception] if the S3 upload fails
#
def upload_log(bucket, key, body, options={})
  # Upload log
  result = AWS::S3.create_client.put_object(
    options.merge(
      bucket: bucket,
      key: key,
      body: body
    )
  )

  # Get presigned URL that expires in one hour
  options = {bucket: bucket, key: key, expires_in: 3600}
  options[:version_id] = result[:version_id] unless result[:version_id].nil?
  Aws::S3::Presigner.new.presigned_url(:get_object, options)
end

在这里,我可以追踪到为什么会这样做的一切:

  1. presigned_url将其params参数传递给@client.build_requestpresigner.rb#L48)。

  2. build_request最终将这些参数推送到它返回的请求的request.context.params上(记录在client/base_spec.rb#L91中)。

  3. 从这里我的理解是模糊的;我希望Aws::Rest::Request::Builder之类的内容传递所有参数以创建Endpoint,并且此操作的特定规则(我无法找到)允许将version_id添加到查询字符串。

  4. 无论如何,它正在发挥作用。感谢指针迈克尔!