确定 Amazon S3 存储桶是否存在 - 适用于 Ruby 的 AWS 开发工具包
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 AWS 服务入门

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

确定 Amazon S3 存储桶是否存在

以下代码示例检查 Amazon S3 中是否存在指定的存储桶并且该存储桶是否可供您访问。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX - License - Identifier: Apache - 2.0 require 'aws-sdk-s3' # Checks to see whether an Amazon Simple Storage Service # (Amazon S3) bucket exists. # # @param s3_client [Aws::S3::Client] An initialized S3 client. # @param bucket_name [String] The name of the bucket. # @return [Boolean] true if the bucket exists; otherwise, false. # @example # exit 1 unless bucket_exists?( # Aws::S3::Client.new(region: 'us-east-1'), # 'doc-example-bucket' # ) def bucket_exists?(s3_client, bucket_name) response = s3_client.list_buckets response.buckets.each do |bucket| return true if bucket.name == bucket_name end return false rescue StandardError => e puts "Error listing buckets: #{e.message}" return false end # Full example call: def run_me bucket_name = 'doc-example-bucket' region = 'us-east-1' s3_client = Aws::S3::Client.new(region: region) if bucket_exists?(s3_client, bucket_name) puts 'Bucket exists.' else puts 'Bucket does not exist or is not accessible to you.' end end run_me if $PROGRAM_NAME == __FILE__

以下代码示例检查 Amazon S3 中是否存在指定的存储桶以及您是否有权访问它。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 require 'aws-sdk-s3' # Determines whether an Amazon Simple Storage Service (Amazon S3) # bucket exists and you have permission to access it. # # Prerequisites: # # - An S3 bucket. # # @param # @param # @return [Boolean] true if the bucket exists and you have permission to # access it; otherwise, false. # @example # exit 1 unless bucket_exists_and_accessible?( # Aws::S3::Client.new(region: 'us-east-1'), # 'doc-example-bucket' # ) def bucket_exists_and_accessible?(s3_client, bucket_name) s3_client.head_bucket(bucket: bucket_name) return true rescue StandardError return false end # Full example call: def run_me bucket_name = 'doc-example-bucket' region = 'us-east-1' s3_client = Aws::S3::Client.new(region: region) if bucket_exists_and_accessible?(s3_client, bucket_name) puts "Bucket '#{bucket_name}' exists and is accessible to you." else puts "Bucket '#{bucket_name}' does not exist " \ 'or is not accessible to you.' end end run_me if $PROGRAM_NAME == __FILE__