-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbucket_create.rb
58 lines (49 loc) · 1.81 KB
/
bucket_create.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# Purpose
#
# Shows how to use the AWS SDK for Ruby to create an Amazon Simple Storage Service (Amazon S3) bucket.
# snippet-start:[s3.ruby.create_bucket_snippet.rb]
require "aws-sdk-s3"
# Wraps Amazon S3 bucket actions.
class BucketCreateWrapper
attr_reader :bucket
# @param bucket [Aws::S3::Bucket] An Amazon S3 bucket initialized with a name. This is a client-side object until
# create is called.
def initialize(bucket)
@bucket = bucket
end
# Creates an Amazon S3 bucket in the specified AWS Region.
#
# @param region [String] The Region where the bucket is created.
# @return [Boolean] True when the bucket is created; otherwise, false.
def create?(region)
@bucket.create(create_bucket_configuration: { location_constraint: region })
true
rescue Aws::Errors::ServiceError => e
puts "Couldn't create bucket. Here's why: #{e.message}"
false
end
# Gets the Region where the bucket is located.
#
# @return [String] The location of the bucket.
def location
if @bucket.nil?
"None. You must create a bucket before you can get its location!"
else
@bucket.client.get_bucket_location(bucket: @bucket.name).location_constraint
end
rescue Aws::Errors::ServiceError => e
"Couldn't get the location of #{@bucket.name}. Here's why: #{e.message}"
end
end
# Example usage:
def run_demo
region = "us-west-2"
wrapper = BucketCreateWrapper.new(Aws::S3::Bucket.new("doc-example-bucket-#{Random.uuid}"))
return unless wrapper.create?(region)
puts "Created bucket #{wrapper.bucket.name}."
puts "Your bucket's region is: #{wrapper.location}"
end
run_demo if $PROGRAM_NAME == __FILE__
# snippet-end:[s3.ruby.create_bucket_snippet.rb]