使用ruby aws-sdk V2指示是否配置了静态网站

时间:2016-01-20 00:07:16

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

我有大量的S3存储桶配置为静态Web托管,我正在尝试使用Ruby aws-sdk迭代列表,以打印各种属性,如索引文档,错误文档,重定向规则等等。

不幸的是,某些存储桶未配置为静态托管。我需要跳过这些桶以避免出错。

我无法弄清楚如何检测是否为静态托管配置了存储区,因此以下代码会引发错误。见下文。

require 'aws-sdk'

s3 = Aws::S3::Resource.new
s3.buckets.take(3).each do |bucket|
  puts "Name = #{bucket.name}"
  puts "Index Document = #{bucket.website.index_document}"
end

返回的错误,因为我没有抓住它是......

The specified bucket does not have a website configuration (Aws::S3::Errors::NoSuchWebsiteConfiguration)

1 个答案:

答案 0 :(得分:0)

我决定采取捷径,抓住错误。

require 'aws-sdk'

s3 = Aws::S3::Resource.new

my_buckets = s3.buckets.map

my_buckets.each do |bucket|
  begin
    puts bucket.name
    puts bucket.website.error_document

  # if a website is not configured it's going to throw an error when you try to access bucket.website.error_document\
  # rescue the error, even though this seems like there should be a more elegant way to handle this.
  rescue Aws::S3::Errors::NoSuchWebsiteConfiguration => e
    puts e.message
  # Buckets that are just there to provide a redirect for www versions of the domain will also throw an error
  rescue Aws::S3::Errors::PermanentRedirect => e
    puts e.message
  rescue Exception => e
    puts e.message
  end
end