Bucket

class aws_cdk.aws_s3.Bucket(scope, id, *, access_control=None, block_public_access=None, bucket_name=None, cors=None, encryption=None, encryption_key=None, inventories=None, lifecycle_rules=None, metrics=None, public_read_access=None, removal_policy=None, server_access_logs_bucket=None, server_access_logs_prefix=None, versioned=None, website_error_document=None, website_index_document=None, website_redirect=None, website_routing_rules=None)

Bases: aws_cdk.core.Resource

An S3 bucket with associated policy objects.

This bucket does not yet have all features that exposed by the underlying BucketResource.

Parameters
  • scope (Construct) –

  • id (str) –

  • access_control (Optional[BucketAccessControl]) – Specifies a canned ACL that grants predefined permissions to the bucket. Default: BucketAccessControl.PRIVATE

  • block_public_access (Optional[BlockPublicAccess]) – The block public access configuration of this bucket. Default: false New buckets and objects don’t allow public access, but users can modify bucket policies or object permissions to allow public access.

  • bucket_name (Optional[str]) – Physical name of this bucket. Default: - Assigned by CloudFormation (recommended).

  • cors (Optional[List[CorsRule]]) – The CORS configuration of this bucket. Default: - No CORS configuration.

  • encryption (Optional[BucketEncryption]) – The kind of server-side encryption to apply to this bucket. If you choose KMS, you can specify a KMS key via encryptionKey. If encryption key is not specified, a key will automatically be created. Default: - Kms if encryptionKey is specified, or Unencrypted otherwise.

  • encryption_key (Optional[IKey]) – External KMS key to use for bucket encryption. The ‘encryption’ property must be either not specified or set to “Kms”. An error will be emitted if encryption is set to “Unencrypted” or “Managed”. Default: - If encryption is set to “Kms” and this property is undefined, a new KMS key will be created and associated with this bucket.

  • inventories (Optional[List[Inventory]]) – The inventory configuration of the bucket. Default: - No inventory configuration

  • lifecycle_rules (Optional[List[LifecycleRule]]) – Rules that define how Amazon S3 manages objects during their lifetime. Default: - No lifecycle rules.

  • metrics (Optional[List[BucketMetrics]]) – The metrics configuration of this bucket. Default: - No metrics configuration.

  • public_read_access (Optional[bool]) – Grants public read access to all objects in the bucket. Similar to calling bucket.grantPublicAccess() Default: false

  • removal_policy (Optional[RemovalPolicy]) – Policy to apply when the bucket is removed from this stack. Default: - The bucket will be orphaned.

  • server_access_logs_bucket (Optional[IBucket]) – Destination bucket for the server access logs. Default: - If “serverAccessLogsPrefix” undefined - access logs disabled, otherwise - log to current bucket.

  • server_access_logs_prefix (Optional[str]) – Optional log file prefix to use for the bucket’s access logs. If defined without “serverAccessLogsBucket”, enables access logs to current bucket with this prefix. Default: - No log file prefix

  • versioned (Optional[bool]) – Whether this bucket should have versioning turned on or not. Default: false

  • website_error_document (Optional[str]) – The name of the error document (e.g. “404.html”) for the website. websiteIndexDocument must also be set if this is set. Default: - No error document.

  • website_index_document (Optional[str]) – The name of the index document (e.g. “index.html”) for the website. Enables static website hosting for this bucket. Default: - No index document.

  • website_redirect (Optional[RedirectTarget]) – Specifies the redirect behavior of all requests to a website endpoint of a bucket. If you specify this property, you can’t specify “websiteIndexDocument”, “websiteErrorDocument” nor , “websiteRoutingRules”. Default: - No redirection.

  • website_routing_rules (Optional[List[RoutingRule]]) – Rules that define when a redirect is applied and the redirect behavior. Default: - No redirection rules.

Methods

add_cors_rule(*, allowed_methods, allowed_origins, allowed_headers=None, exposed_headers=None, id=None, max_age=None)

Adds a cross-origin access configuration for objects in an Amazon S3 bucket.

Parameters
  • allowed_methods (List[HttpMethods]) – An HTTP method that you allow the origin to execute.

  • allowed_origins (List[str]) – One or more origins you want customers to be able to access the bucket from.

  • allowed_headers (Optional[List[str]]) – Headers that are specified in the Access-Control-Request-Headers header. Default: - No headers allowed.

  • exposed_headers (Optional[List[str]]) – One or more headers in the response that you want customers to be able to access from their applications. Default: - No headers exposed.

  • id (Optional[str]) – A unique identifier for this rule. Default: - No id specified.

  • max_age (Union[int, float, None]) – The time in seconds that your browser is to cache the preflight response for the specified resource. Default: - No caching.

Return type

None

add_event_notification(event, dest, *filters)

Adds a bucket notification event destination.

Parameters
  • event (EventType) – The event to trigger the notification.

  • dest (IBucketNotificationDestination) – The notification destination (Lambda, SNS Topic or SQS Queue).

  • filters (NotificationKeyFilter) – S3 object key filter rules to determine which objects trigger this event. Each filter must include a prefix and/or suffix that will be matched against the s3 object key. Refer to the S3 Developer Guide for details about allowed filter rules.

See

https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html

Example:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
bucket.add_event_notification(EventType.OnObjectCreated, my_lambda, "home/myusername/*")
Return type

None

add_inventory(*, destination, enabled=None, format=None, frequency=None, include_object_versions=None, inventory_id=None, objects_prefix=None, optional_fields=None)

Add an inventory configuration.

Parameters
  • destination (InventoryDestination) – The destination of the inventory.

  • enabled (Optional[bool]) – Whether the inventory is enabled or disabled. Default: true

  • format (Optional[InventoryFormat]) – The format of the inventory. Default: InventoryFormat.CSV

  • frequency (Optional[InventoryFrequency]) – Frequency at which the inventory should be generated. Default: InventoryFrequency.WEEKLY

  • include_object_versions (Optional[InventoryObjectVersion]) – If the inventory should contain all the object versions or only the current one. Default: InventoryObjectVersion.ALL

  • inventory_id (Optional[str]) – The inventory configuration ID. Default: - generated ID.

  • objects_prefix (Optional[str]) – The inventory will only include objects that meet the prefix filter criteria. Default: - No objects prefix

  • optional_fields (Optional[List[str]]) – A list of optional fields to be included in the inventory result. Default: - No optional fields.

Return type

None

add_lifecycle_rule(*, abort_incomplete_multipart_upload_after=None, enabled=None, expiration=None, expiration_date=None, id=None, noncurrent_version_expiration=None, noncurrent_version_transitions=None, prefix=None, tag_filters=None, transitions=None)

Add a lifecycle rule to the bucket.

Parameters
  • abort_incomplete_multipart_upload_after (Optional[Duration]) – Specifies a lifecycle rule that aborts incomplete multipart uploads to an Amazon S3 bucket. The AbortIncompleteMultipartUpload property type creates a lifecycle rule that aborts incomplete multipart uploads to an Amazon S3 bucket. When Amazon S3 aborts a multipart upload, it deletes all parts associated with the multipart upload. Default: Incomplete uploads are never aborted

  • enabled (Optional[bool]) – Whether this rule is enabled. Default: true

  • expiration (Optional[Duration]) – Indicates the number of days after creation when objects are deleted from Amazon S3 and Amazon Glacier. If you specify an expiration and transition time, you must use the same time unit for both properties (either in days or by date). The expiration time must also be later than the transition time. Default: No expiration timeout

  • expiration_date (Optional[datetime]) – Indicates when objects are deleted from Amazon S3 and Amazon Glacier. The date value must be in ISO 8601 format. The time is always midnight UTC. If you specify an expiration and transition time, you must use the same time unit for both properties (either in days or by date). The expiration time must also be later than the transition time. Default: No expiration date

  • id (Optional[str]) – A unique identifier for this rule. The value cannot be more than 255 characters.

  • noncurrent_version_expiration (Optional[Duration]) – Time between when a new version of the object is uploaded to the bucket and when old versions of the object expire. For buckets with versioning enabled (or suspended), specifies the time, in days, between when a new version of the object is uploaded to the bucket and when old versions of the object expire. When object versions expire, Amazon S3 permanently deletes them. If you specify a transition and expiration time, the expiration time must be later than the transition time. Default: No noncurrent version expiration

  • noncurrent_version_transitions (Optional[List[NoncurrentVersionTransition]]) – One or more transition rules that specify when non-current objects transition to a specified storage class. Only for for buckets with versioning enabled (or suspended). If you specify a transition and expiration time, the expiration time must be later than the transition time.

  • prefix (Optional[str]) – Object key prefix that identifies one or more objects to which this rule applies. Default: Rule applies to all objects

  • tag_filters (Optional[Mapping[str, Any]]) – The TagFilter property type specifies tags to use to identify a subset of objects for an Amazon S3 bucket. Default: Rule applies to all objects

  • transitions (Optional[List[Transition]]) – One or more transition rules that specify when an object transitions to a specified storage class. If you specify an expiration and transition time, you must use the same time unit for both properties (either in days or by date). The expiration time must also be later than the transition time. Default: No transition rules

Return type

None

add_metric(*, id, prefix=None, tag_filters=None)

Adds a metrics configuration for the CloudWatch request metrics from the bucket.

Parameters
  • id (str) – The ID used to identify the metrics configuration.

  • prefix (Optional[str]) – The prefix that an object must have to be included in the metrics results.

  • tag_filters (Optional[Mapping[str, Any]]) – Specifies a list of tag filters to use as a metrics configuration filter. The metrics configuration includes only objects that meet the filter’s criteria.

Return type

None

add_object_created_notification(dest, *filters)

Subscribes a destination to receive notifications when an object is created in the bucket.

This is identical to calling onEvent(EventType.ObjectCreated).

Parameters
Return type

None

add_object_removed_notification(dest, *filters)

Subscribes a destination to receive notifications when an object is removed from the bucket.

This is identical to calling onEvent(EventType.ObjectRemoved).

Parameters
Return type

None

add_to_resource_policy(permission)

Adds a statement to the resource policy for a principal (i.e. account/role/service) to perform actions on this bucket and/or it’s contents. Use bucketArn and arnForObjects(keys) to obtain ARNs for this bucket or objects.

Parameters

permission (PolicyStatement) –

Return type

AddToResourcePolicyResult

arn_for_objects(key_pattern)

Returns an ARN that represents all objects within the bucket that match the key pattern specified.

To represent all keys, specify "*".

If you need to specify a keyPattern with multiple components, concatenate them into a single string, e.g.:

arnForObjects(home/${team}/${user}/*)

Parameters

key_pattern (str) –

Return type

str

grant_delete(identity, objects_key_pattern=None)

Grants s3:DeleteObject* permission to an IAM pricipal for objects in this bucket.

Parameters
  • identity (IGrantable) – The principal.

  • objects_key_pattern (Optional[Any]) – Restrict the permission to a certain key pattern (default ‘*’).

Return type

Grant

grant_public_access(key_prefix=None, *allowed_actions)

Allows unrestricted access to objects from this bucket.

IMPORTANT: This permission allows anyone to perform actions on S3 objects in this bucket, which is useful for when you configure your bucket as a website and want everyone to be able to read objects in the bucket without needing to authenticate.

Without arguments, this method will grant read (“s3:GetObject”) access to all objects (“*”) in the bucket.

The method returns the iam.Grant object, which can then be modified as needed. For example, you can add a condition that will restrict access only to an IPv4 range like this:

const grant = bucket.grantPublicAccess();
grant.resourceStatement!.addCondition(‘IpAddress’, { “aws:SourceIp”: “54.240.143.0/24” });
Parameters
  • key_prefix (Optional[str]) – the prefix of S3 object keys (e.g. home/*). Default is “*”.

  • allowed_actions (str) – the set of S3 actions to allow. Default is “s3:GetObject”.

Return type

Grant

grant_put(identity, objects_key_pattern=None)

Grants s3:PutObject* and s3:Abort* permissions for this bucket to an IAM principal.

If encryption is used, permission to use the key to encrypt the contents of written files will also be granted to the same principal.

Parameters
  • identity (IGrantable) – The principal.

  • objects_key_pattern (Optional[Any]) – Restrict the permission to a certain key pattern (default ‘*’).

Return type

Grant

grant_read(identity, objects_key_pattern=None)

Grant read permissions for this bucket and it’s contents to an IAM principal (Role/Group/User).

If encryption is used, permission to use the key to decrypt the contents of the bucket will also be granted to the same principal.

Parameters
  • identity (IGrantable) – The principal.

  • objects_key_pattern (Optional[Any]) – Restrict the permission to a certain key pattern (default ‘*’).

Return type

Grant

grant_read_write(identity, objects_key_pattern=None)

Grants read/write permissions for this bucket and it’s contents to an IAM principal (Role/Group/User).

If an encryption key is used, permission to use the key for encrypt/decrypt will also be granted.

Parameters
  • identity (IGrantable) – The principal.

  • objects_key_pattern (Optional[Any]) – Restrict the permission to a certain key pattern (default ‘*’).

Return type

Grant

grant_write(identity, objects_key_pattern=None)

Grant write permissions to this bucket to an IAM principal.

If encryption is used, permission to use the key to encrypt the contents of written files will also be granted to the same principal.

Parameters
  • identity (IGrantable) – The principal.

  • objects_key_pattern (Optional[Any]) – Restrict the permission to a certain key pattern (default ‘*’).

Return type

Grant

on_cloud_trail_event(id, *, paths=None, description=None, event_pattern=None, rule_name=None, target=None)

Define a CloudWatch event that triggers when something happens to this repository.

Requires that there exists at least one CloudTrail Trail in your account that captures the event. This method will not create the Trail.

Parameters
  • id (str) – The id of the rule.

  • paths (Optional[List[str]]) – Only watch changes to these object paths. Default: - Watch changes to all objects

  • description (Optional[str]) – A description of the rule’s purpose. Default: - No description

  • event_pattern (Optional[EventPattern]) – Additional restrictions for the event to route to the specified target. The method that generates the rule probably imposes some type of event filtering. The filtering implied by what you pass here is added on top of that filtering. Default: - No additional filtering based on an event pattern.

  • rule_name (Optional[str]) – A name for the rule. Default: AWS CloudFormation generates a unique physical ID.

  • target (Optional[IRuleTarget]) – The target to register for the event. Default: - No target is added to the rule. Use addTarget() to add a target.

Return type

Rule

on_cloud_trail_put_object(id, *, paths=None, description=None, event_pattern=None, rule_name=None, target=None)

Defines an AWS CloudWatch event that triggers when an object is uploaded to the specified paths (keys) in this bucket using the PutObject API call.

Note that some tools like aws s3 cp will automatically use either PutObject or the multipart upload API depending on the file size, so using onCloudTrailWriteObject may be preferable.

Requires that there exists at least one CloudTrail Trail in your account that captures the event. This method will not create the Trail.

Parameters
  • id (str) – The id of the rule.

  • paths (Optional[List[str]]) – Only watch changes to these object paths. Default: - Watch changes to all objects

  • description (Optional[str]) – A description of the rule’s purpose. Default: - No description

  • event_pattern (Optional[EventPattern]) – Additional restrictions for the event to route to the specified target. The method that generates the rule probably imposes some type of event filtering. The filtering implied by what you pass here is added on top of that filtering. Default: - No additional filtering based on an event pattern.

  • rule_name (Optional[str]) – A name for the rule. Default: AWS CloudFormation generates a unique physical ID.

  • target (Optional[IRuleTarget]) – The target to register for the event. Default: - No target is added to the rule. Use addTarget() to add a target.

Return type

Rule

on_cloud_trail_write_object(id, *, paths=None, description=None, event_pattern=None, rule_name=None, target=None)

Defines an AWS CloudWatch event that triggers when an object at the specified paths (keys) in this bucket are written to.

This includes the events PutObject, CopyObject, and CompleteMultipartUpload.

Note that some tools like aws s3 cp will automatically use either PutObject or the multipart upload API depending on the file size, so using this method may be preferable to onCloudTrailPutObject.

Requires that there exists at least one CloudTrail Trail in your account that captures the event. This method will not create the Trail.

Parameters
  • id (str) – The id of the rule.

  • paths (Optional[List[str]]) – Only watch changes to these object paths. Default: - Watch changes to all objects

  • description (Optional[str]) – A description of the rule’s purpose. Default: - No description

  • event_pattern (Optional[EventPattern]) – Additional restrictions for the event to route to the specified target. The method that generates the rule probably imposes some type of event filtering. The filtering implied by what you pass here is added on top of that filtering. Default: - No additional filtering based on an event pattern.

  • rule_name (Optional[str]) – A name for the rule. Default: AWS CloudFormation generates a unique physical ID.

  • target (Optional[IRuleTarget]) – The target to register for the event. Default: - No target is added to the rule. Use addTarget() to add a target.

Return type

Rule

s3_url_for_object(key=None)

The S3 URL of an S3 object.

For example:

Parameters

key (Optional[str]) – The S3 key of the object. If not specified, the S3 URL of the bucket is returned.

Return type

str

Returns

an ObjectS3Url token

Example:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
s3:
to_string()

Returns a string representation of this construct.

Return type

str

url_for_object(key=None)

The https URL of an S3 object.

Specify regional: false at the options for non-regional URLs. For example:

Parameters

key (Optional[str]) – The S3 key of the object. If not specified, the URL of the bucket is returned.

Return type

str

Returns

an ObjectS3Url token

Example:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
https:
virtual_hosted_url_for_object(key=None, *, regional=None)

The virtual hosted-style URL of an S3 object.

Specify regional: false at the options for non-regional URL. For example:

Parameters
  • key (Optional[str]) – The S3 key of the object. If not specified, the URL of the bucket is returned.

  • regional (Optional[bool]) – Specifies the URL includes the region. Default: - true

Return type

str

Returns

an ObjectS3Url token

Example:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
https:

Attributes

bucket_arn

The ARN of the bucket.

Return type

str

bucket_domain_name

The IPv4 DNS name of the specified bucket.

Return type

str

bucket_dual_stack_domain_name

The IPv6 DNS name of the specified bucket.

Return type

str

bucket_name

The name of the bucket.

Return type

str

bucket_regional_domain_name

The regional domain name of the specified bucket.

Return type

str

bucket_website_domain_name

The Domain name of the static website.

Return type

str

bucket_website_url

The URL of the static website.

Return type

str

encryption_key

Optional KMS encryption key associated with this bucket.

Return type

Optional[IKey]

env

The environment this resource belongs to.

For resources that are created and managed by the CDK (generally, those created by creating new class instances like Role, Bucket, etc.), this is always the same as the environment of the stack they belong to; however, for imported resources (those obtained from static methods like fromRoleArn, fromBucketName, etc.), that might be different than the stack they were imported into.

Return type

ResourceEnvironment

is_website

If this bucket has been configured for static website hosting.

Return type

Optional[bool]

node

The construct tree node associated with this construct.

Return type

ConstructNode

policy

The resource policy associated with this bucket.

If autoCreatePolicy is true, a BucketPolicy will be created upon the first call to addToResourcePolicy(s).

Return type

Optional[BucketPolicy]

stack

The stack in which this resource is defined.

Return type

Stack

Static Methods

classmethod from_bucket_arn(scope, id, bucket_arn)
Parameters
  • scope (Construct) –

  • id (str) –

  • bucket_arn (str) –

Return type

IBucket

classmethod from_bucket_attributes(scope, id, *, account=None, bucket_arn=None, bucket_domain_name=None, bucket_dual_stack_domain_name=None, bucket_name=None, bucket_regional_domain_name=None, bucket_website_new_url_format=None, bucket_website_url=None, encryption_key=None, is_website=None, region=None)

Creates a Bucket construct that represents an external bucket.

Parameters
  • scope (Construct) – The parent creating construct (usually this).

  • id (str) – The construct’s name.

  • account (Optional[str]) – The account this existing bucket belongs to. Default: - it’s assumed the bucket belongs to the same account as the scope it’s being imported into

  • bucket_arn (Optional[str]) – The ARN of the bucket. At least one of bucketArn or bucketName must be defined in order to initialize a bucket ref.

  • bucket_domain_name (Optional[str]) – The domain name of the bucket. Default: Inferred from bucket name

  • bucket_dual_stack_domain_name (Optional[str]) – The IPv6 DNS name of the specified bucket.

  • bucket_name (Optional[str]) – The name of the bucket. If the underlying value of ARN is a string, the name will be parsed from the ARN. Otherwise, the name is optional, but some features that require the bucket name such as auto-creating a bucket policy, won’t work.

  • bucket_regional_domain_name (Optional[str]) – The regional domain name of the specified bucket.

  • bucket_website_new_url_format (Optional[bool]) – The format of the website URL of the bucket. This should be true for regions launched since 2014. Default: false

  • bucket_website_url (Optional[str]) – The website URL of the bucket (if static web hosting is enabled). Default: Inferred from bucket name

  • encryption_key (Optional[IKey]) –

  • is_website (Optional[bool]) – If this bucket has been configured for static website hosting. Default: false

  • region (Optional[str]) – The region this existing bucket is in. Default: - it’s assumed the bucket is in the same region as the scope it’s being imported into

Return type

IBucket

classmethod from_bucket_name(scope, id, bucket_name)
Parameters
  • scope (Construct) –

  • id (str) –

  • bucket_name (str) –

Return type

IBucket

classmethod is_construct(x)

Return whether the given object is a Construct.

Parameters

x (Any) –

Return type

bool