You are viewing documentation for version 2 of the AWS SDK for Ruby. Version 3 documentation can be found here.

Class: Aws::S3::Bucket

Inherits:
Resources::Resource show all
Defined in:
aws-sdk-resources/lib/aws-sdk-resources/services/s3/bucket.rb

Instance Attribute Summary collapse

Attributes inherited from Resources::Resource

#client, #identifiers

Instance Method Summary collapse

Methods inherited from Resources::Resource

add_data_attribute, add_identifier, #data, data_attributes, #data_loaded?, identifiers, #wait_until

Methods included from Resources::OperationMethods

#add_batch_operation, #add_operation, #batch_operation, #batch_operation_names, #batch_operations, #operation, #operation_names, #operations

Constructor Details

#initialize(name, options = {}) ⇒ Object #initialize(options = {}) ⇒ Object

Overloads:

  • #initialize(name, options = {}) ⇒ Object

    Parameters:

    • name (String)

    Options Hash (options):

    • :client (Client)

      When `:client is not given, the options hash is used to construct a new Client object.

  • #initialize(options = {}) ⇒ Object

    Options Hash (options):

    • :name (required, String)
    • :client (Client)

      When `:client is not given, the options hash is used to construct a new Client object.

Instance Attribute Details

#creation_dateTime (readonly)

Date the bucket was created.

Returns:

  • (Time)

    Date the bucket was created.

#nameString (readonly)

Returns:

  • (String)

Instance Method Details

#aclBucketAcl

Returns:

#clear!void

This method returns an undefined value.

Deletes all objects and versioned objects from this bucket

Examples:


bucket.clear!


14
15
16
# File 'aws-sdk-resources/lib/aws-sdk-resources/services/s3/bucket.rb', line 14

def clear!
  object_versions.batch_delete!
end

#corsBucketCors

Returns:

#create(options = {}) ⇒ Types::CreateBucketOutput

Creates a new bucket.

Examples:

Request syntax example with placeholder values


bucket.create({
  acl: "private", # accepts private, public-read, public-read-write, authenticated-read
  create_bucket_configuration: {
    location_constraint: "EU", # accepts EU, eu-west-1, us-west-1, us-west-2, ap-south-1, ap-southeast-1, ap-southeast-2, ap-northeast-1, sa-east-1, cn-north-1, eu-central-1
  },
  grant_full_control: "GrantFullControl",
  grant_read: "GrantRead",
  grant_read_acp: "GrantReadACP",
  grant_write: "GrantWrite",
  grant_write_acp: "GrantWriteACP",
})

Options Hash (options):

  • :acl (String)

    The canned ACL to apply to the bucket.

  • :create_bucket_configuration (Types::CreateBucketConfiguration)
  • :grant_full_control (String)

    Allows grantee the read, write, read ACP, and write ACP permissions on the bucket.

  • :grant_read (String)

    Allows grantee to list the objects in the bucket.

  • :grant_read_acp (String)

    Allows grantee to read the bucket ACL.

  • :grant_write (String)

    Allows grantee to create, overwrite, and delete any object in the bucket.

  • :grant_write_acp (String)

    Allows grantee to write the ACL for the applicable bucket.

Returns:

See Also:

#deleteStruct

Deletes the bucket. All objects (including all object versions and Delete Markers) in the bucket must be deleted before the bucket itself can be deleted.

Examples:

Request syntax example with placeholder values


bucket.delete()

Returns:

  • (Struct)

    Returns an empty response.

See Also:

#delete!(options = { }) ⇒ void

This method returns an undefined value.

Deletes all objects and versioned objects from this bucket and then deletes the bucket.

Examples:


bucket.delete!

Parameters:

  • options (Hash) (defaults to: { })

    a customizable set of options

Options Hash (options):

  • :max_attempts (Integer) — default: 3

    Maximum number of times to attempt to delete the empty bucket before raising Aws::S3::Errors::BucketNotEmpty.

  • :initial_wait (Float) — default: 1.3

    Seconds to wait before retrying the call to delete the bucket, exponentially increased for each attempt.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'aws-sdk-resources/lib/aws-sdk-resources/services/s3/bucket.rb', line 34

def delete! options = { }
  options = {
    initial_wait: 1.3,
    max_attempts: 3,
  }.merge(options)

  attempts = 0
  begin
    clear!
    delete
  rescue Errors::BucketNotEmpty
    attempts += 1
    if attempts >= options[:max_attempts]
      raise
    else
      Kernel.sleep(options[:initial_wait] ** attempts)
      retry
    end
  end
end

#delete_objects(options = {}) ⇒ Types::DeleteObjectsOutput

This operation enables you to delete multiple objects from a bucket using a single HTTP request. You may specify up to 1000 keys.

Examples:

Request syntax example with placeholder values


bucket.delete_objects({
  delete: { # required
    objects: [ # required
      {
        key: "ObjectKey", # required
        version_id: "ObjectVersionId",
      },
    ],
    quiet: false,
  },
  mfa: "MFA",
  request_payer: "requester", # accepts requester
  use_accelerate_endpoint: false,
})

Options Hash (options):

Returns:

See Also:

#exists?Boolean

Returns true if this Bucket exists. Returns false otherwise.

Returns:

  • (Boolean)

    Returns true if this Bucket exists. Returns false otherwise.

#lifecycleBucketLifecycle

Returns:

#lifecycle_configurationBucketLifecycleConfiguration

#loggingBucketLogging

Returns:

#multipart_uploads(options = {}) ⇒ Collection<MultipartUpload>

Returns a Collection of MultipartUpload resources. No API requests are made until you call an enumerable method on the collection. Client#list_multipart_uploads will be called multiple times until every MultipartUpload has been yielded.

Examples:

Request syntax example with placeholder values


bucket.multipart_uploads({
  delimiter: "Delimiter",
  encoding_type: "url", # accepts url
  key_marker: "KeyMarker",
  max_uploads: 1,
  prefix: "Prefix",
  upload_id_marker: "UploadIdMarker",
  use_accelerate_endpoint: false,
})

Enumerating MultipartUpload resources.

bucket.multipart_uploads.each do |multipartupload|
  # yields each multipartupload
end

Enumerating MultipartUpload resources with a limit.

bucket.multipart_uploads.limit(10).each do |multipartupload|
  # yields at most 10 multipart_uploads
end

Options Hash (options):

  • :delimiter (String)

    Character you use to group keys.

  • :encoding_type (String)

    Requests Amazon S3 to encode the object keys in the response and specifies the encoding method to use. An object key may contain any Unicode character; however, XML 1.0 parser cannot parse some characters, such as characters with an ASCII value from 0 to 10. For characters that are not supported in XML 1.0, you can add this parameter to request that Amazon S3 encode the keys in the response.

  • :key_marker (String)

    Together with upload-id-marker, this parameter specifies the multipart upload after which listing should begin.

  • :max_uploads (Integer)

    Sets the maximum number of multipart uploads, from 1 to 1,000, to return in the response body. 1,000 is the maximum number of uploads that can be returned in a response.

  • :prefix (String)

    Lists in-progress uploads only for those keys that begin with the specified prefix.

  • :upload_id_marker (String)

    Together with key-marker, specifies the multipart upload after which listing should begin. If key-marker is not specified, the upload-id-marker parameter is ignored.

  • :use_accelerate_endpoint (Boolean)

    When true, the "https://BUCKETNAME.s3-accelerate.amazonaws.com" endpoint will be used.

Returns:

See Also:

#notificationBucketNotification

Returns:

#object(key) ⇒ Object

Parameters:

Returns:

See Also:

#object_versions(options = {}) ⇒ Collection<ObjectVersion>

Returns a Collection of ObjectVersion resources. No API requests are made until you call an enumerable method on the collection. Client#list_object_versions will be called multiple times until every ObjectVersion has been yielded.

Examples:

Request syntax example with placeholder values


bucket.object_versions({
  delimiter: "Delimiter",
  encoding_type: "url", # accepts url
  key_marker: "KeyMarker",
  max_keys: 1,
  prefix: "Prefix",
  version_id_marker: "VersionIdMarker",
  use_accelerate_endpoint: false,
})

Enumerating ObjectVersion resources.

bucket.object_versions.each do |objectversion|
  # yields each objectversion
end

Enumerating ObjectVersion resources with a limit.

bucket.object_versions.limit(10).each do |objectversion|
  # yields at most 10 object_versions
end

Batch operations callable on the returned collection


# calls Client#delete_objects on each batch
bucket.object_versions.batch_delete!

Options Hash (options):

  • :delimiter (String)

    A delimiter is a character you use to group keys.

  • :encoding_type (String)

    Requests Amazon S3 to encode the object keys in the response and specifies the encoding method to use. An object key may contain any Unicode character; however, XML 1.0 parser cannot parse some characters, such as characters with an ASCII value from 0 to 10. For characters that are not supported in XML 1.0, you can add this parameter to request that Amazon S3 encode the keys in the response.

  • :key_marker (String)

    Specifies the key to start with when listing objects in a bucket.

  • :max_keys (Integer)

    Sets the maximum number of keys returned in the response. The response might contain fewer keys but will never contain more.

  • :prefix (String)

    Limits the response to keys that begin with the specified prefix.

  • :version_id_marker (String)

    Specifies the object version you want to start listing from.

  • :use_accelerate_endpoint (Boolean)

    When true, the "https://BUCKETNAME.s3-accelerate.amazonaws.com" endpoint will be used.

Returns:

See Also:

#objects(options = {}) ⇒ Collection<ObjectSummary>

Returns a Collection of ObjectSummary resources. No API requests are made until you call an enumerable method on the collection. Client#list_objects will be called multiple times until every ObjectSummary has been yielded.

Examples:

Request syntax example with placeholder values


bucket.objects({
  delimiter: "Delimiter",
  encoding_type: "url", # accepts url
  marker: "Marker",
  max_keys: 1,
  prefix: "Prefix",
  request_payer: "requester", # accepts requester
  use_accelerate_endpoint: false,
})

Enumerating ObjectSummary resources.

bucket.objects.each do |objectsummary|
  # yields each objectsummary
end

Enumerating ObjectSummary resources with a limit.

bucket.objects.limit(10).each do |objectsummary|
  # yields at most 10 objects
end

Batch operations callable on the returned collection


# calls Client#delete_objects on each batch
bucket.objects.batch_delete!

Options Hash (options):

  • :delimiter (String)

    A delimiter is a character you use to group keys.

  • :encoding_type (String)

    Requests Amazon S3 to encode the object keys in the response and specifies the encoding method to use. An object key may contain any Unicode character; however, XML 1.0 parser cannot parse some characters, such as characters with an ASCII value from 0 to 10. For characters that are not supported in XML 1.0, you can add this parameter to request that Amazon S3 encode the keys in the response.

  • :marker (String)

    Specifies the key to start with when listing objects in a bucket.

  • :max_keys (Integer)

    Sets the maximum number of keys returned in the response. The response might contain fewer keys but will never contain more.

  • :prefix (String)

    Limits the response to keys that begin with the specified prefix.

  • :request_payer (String)

    Confirms that the requester knows that she or he will be charged for the list objects request. Bucket owners need not specify this parameter in their requests.

  • :use_accelerate_endpoint (Boolean)

    When true, the "https://BUCKETNAME.s3-accelerate.amazonaws.com" endpoint will be used.

Returns:

See Also:

#policyBucketPolicy

Returns:

#presigned_post(options = {}) ⇒ PresignedPost

Note:

You must specify :key or :key_starts_with. All other options are optional.

Creates a PresignedPost that makes it easy to upload a file from a web browser direct to Amazon S3 using an HTML post form with a file field.

See the PresignedPost documentation for more information.

Options Hash (options):

Returns:

See Also:



91
92
93
94
95
96
97
98
# File 'aws-sdk-resources/lib/aws-sdk-resources/services/s3/bucket.rb', line 91

def presigned_post(options = {})
  PresignedPost.new(
    client.config.credentials,
    client.config.region,
    name,
    {url: url}.merge(options)
  )
end

#put_object(options = {}) ⇒ Object

Examples:

Request syntax example with placeholder values


bucket.put_object({
  acl: "private", # accepts private, public-read, public-read-write, authenticated-read, aws-exec-read, bucket-owner-read, bucket-owner-full-control
  body: source_file, # file/IO object, or string data
  cache_control: "CacheControl",
  content_disposition: "ContentDisposition",
  content_encoding: "ContentEncoding",
  content_language: "ContentLanguage",
  content_length: 1,
  content_md5: "ContentMD5",
  content_type: "ContentType",
  expires: Time.now,
  grant_full_control: "GrantFullControl",
  grant_read: "GrantRead",
  grant_read_acp: "GrantReadACP",
  grant_write_acp: "GrantWriteACP",
  key: "ObjectKey", # required
  metadata: {
    "MetadataKey" => "MetadataValue",
  },
  server_side_encryption: "AES256", # accepts AES256, aws:kms
  storage_class: "STANDARD", # accepts STANDARD, REDUCED_REDUNDANCY, STANDARD_IA
  website_redirect_location: "WebsiteRedirectLocation",
  sse_customer_algorithm: "SSECustomerAlgorithm",
  sse_customer_key: "SSECustomerKey",
  sse_customer_key_md5: "SSECustomerKeyMD5",
  ssekms_key_id: "SSEKMSKeyId",
  request_payer: "requester", # accepts requester
  tagging: "TaggingHeader",
  use_accelerate_endpoint: false,
})

Basic usage

object = bucket.put_object(options)
object.key
#=> "object-key"

Options Hash (options):

  • :acl (String)

    The canned ACL to apply to the object.

  • :body (IO, String)

    Object data.

  • :cache_control (String)

    Specifies caching behavior along the request/reply chain.

  • :content_disposition (String)

    Specifies presentational information for the object.

  • :content_encoding (String)

    Specifies what content encodings have been applied to the object and thus what decoding mechanisms must be applied to obtain the media-type referenced by the Content-Type header field.

  • :content_language (String)

    The language the content is in.

  • :content_length (Integer)

    Size of the body in bytes. This parameter is useful when the size of the body cannot be determined automatically.

  • :content_md5 (String)

    The base64-encoded 128-bit MD5 digest of the part data.

  • :content_type (String)

    A standard MIME type describing the format of the object data.

  • :expires (Time)

    The date and time at which the object is no longer cacheable.

  • :grant_full_control (String)

    Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object.

  • :grant_read (String)

    Allows grantee to read the object data and its metadata.

  • :grant_read_acp (String)

    Allows grantee to read the object ACL.

  • :grant_write_acp (String)

    Allows grantee to write the ACL for the applicable object.

  • :key (required, String)

    Object key for which the PUT operation was initiated.

  • :metadata (Hash<String,String>)

    A map of metadata to store with the object in S3.

  • :server_side_encryption (String)

    The Server-side encryption algorithm used when storing this object in S3 (e.g., AES256, aws:kms).

  • :storage_class (String)

    The type of storage to use for the object. Defaults to \'STANDARD\'.

  • :website_redirect_location (String)

    If the bucket is configured as a website, redirects requests for this object to another object in the same bucket or to an external URL. Amazon S3 stores the value of this header in the object metadata.

  • :sse_customer_algorithm (String)

    Specifies the algorithm to use to when encrypting the object (e.g., AES256).

  • :sse_customer_key (String)

    Specifies the customer-provided encryption key for Amazon S3 to use in encrypting data. This value is used to store the object and then it is discarded; Amazon does not store the encryption key. The key must be appropriate for use with the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm header.

  • :sse_customer_key_md5 (String)

    Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. Amazon S3 uses this header for a message integrity check to ensure the encryption key was transmitted without error.

  • :ssekms_key_id (String)

    Specifies the AWS KMS key ID to use for object encryption. All GET and PUT requests for an object protected by AWS KMS will fail if not made via SSL or using SigV4. Documentation on configuring any of the officially supported AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version

  • :request_payer (String)

    Confirms that the requester knows that she or he will be charged for the request. Bucket owners need not specify this parameter in their requests. Documentation on downloading objects from requester pays buckets can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html

  • :tagging (String)

    The tag-set for the object. The tag-set must be encoded as URL Query parameters

  • :use_accelerate_endpoint (Boolean)

    When true, the "https://BUCKETNAME.s3-accelerate.amazonaws.com" endpoint will be used.

Returns:

See Also:

#request_paymentBucketRequestPayment

#taggingBucketTagging

Returns:

#url(options = {}) ⇒ String

Returns a public URL for this bucket.

bucket = s3.bucket('bucket-name')
bucket.url
#=> "https://bucket-name.s3.amazonaws.com"

You can pass virtual_host: true to use the bucket name as the host name.

bucket = s3.bucket('my.bucket.com', virtual_host: true)
bucket.url
#=> "http://my.bucket.com"

Parameters:

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :virtual_host (Boolean) — default: false

    When true, the bucket name will be used as the host name. This is useful when you have a CNAME configured for this bucket.

Returns:

  • (String)

    the URL for this bucket.



73
74
75
76
77
78
79
# File 'aws-sdk-resources/lib/aws-sdk-resources/services/s3/bucket.rb', line 73

def url(options = {})
  if options[:virtual_host]
    "http://#{name}"
  else
    s3_bucket_url
  end
end

#versioningBucketVersioning

Returns:

#wait_until_exists {|waiter| ... } ⇒ Bucket

Waits until this Bucket is exists. This method waits by polling Client#head_bucket until successful. An error is raised after a configurable number of failed checks.

This waiter uses the following defaults:

Configuration Default
#delay 5
#max_attempts 20

You can modify defaults and register callbacks by passing a block argument.

Examples:

Basic usage

bucket.wait_until_exists

Yield Parameters:

Returns:

  • (Bucket)

    Returns a copy of this Bucket that is not loaded.

Raises:

See Also:

#wait_until_not_exists {|waiter| ... } ⇒ Bucket

Waits until this Bucket is not_exists. This method waits by polling Client#head_bucket until successful. An error is raised after a configurable number of failed checks.

This waiter uses the following defaults:

Configuration Default
#delay 5
#max_attempts 20

You can modify defaults and register callbacks by passing a block argument.

Examples:

Basic usage

bucket.wait_until_not_exists

Yield Parameters:

Returns:

  • (Bucket)

    Returns a copy of this Bucket that is not loaded.

Raises:

See Also:

#websiteBucketWebsite

Returns: