AWS SDK for Ruby
Developer Guide

Determining Whether an Amazon S3 Bucket Exists

There are two cases in which you would want to determine whether a bucket already exists. You perform these tests in lieu of receiving an exception if the condition fails:

  • You want to determine whether a bucket with a specific name already exists among all buckets, even ones to which you do not have access. This test helps prevent you from trying to create a bucket with the name of an existing bucket, which causes an exception.

  • You want to perform an operation, such as add an item to a bucket, only on a bucket to which you have access.

The following example sets bucket_exists to true if a bucket with the name my-bucket already exists. The region: parameter to Resource has no effect on the result.

require 'aws-sdk-s3' # v2: require 'aws-sdk' s3 = Aws::S3::Resource.new(region: 'us-west-2') bucket_exists = s3.bucket('my-bucket').exists?

The following example sets bucket_exists to true if the bucket with the name my-bucket exists and you have access to the bucket. Again, the region parameter to Client has no effect on the result.

require 'aws-sdk-s3' # v2: require 'aws-sdk' client = Aws::S3::Client.new(region: 'us-west-2') begin client.head_bucket({bucket: 'bucket_name', use_accelerate_endpoint: false}) # We know bucket exists rescue StandardError puts 'Bucket does not exist' end