BucketBase
- class aws_cdk.aws_s3.BucketBase(scope, id, *, account=None, environment_from_arn=None, physical_name=None, region=None)
Bases:
ResourceRepresents an S3 Bucket.
Buckets can be either defined within this stack:
new Bucket(this, ‘MyBucket’, { props });
Or imported from an existing bucket:
Bucket.import(this, ‘MyImportedBucket’, { bucketArn: … });
You can also export a bucket and import it into another stack:
const ref = myBucket.export(); Bucket.import(this, ‘MyImportedBucket’, ref);
- Parameters:
scope (
Construct)id (
str)account (
Optional[str]) – The AWS account ID this resource belongs to. Default: - the resource is in the same account as the stack it belongs toenvironment_from_arn (
Optional[str]) – ARN to deduce region and account from. The ARN is parsed and the account and region are taken from the ARN. This should be used for imported resources. Cannot be supplied together with eitheraccountorregion. Default: - take environment fromaccount,regionparameters, or use Stack environment.physical_name (
Optional[str]) – The value passed in by users to the physical name prop of the resource. -undefinedimplies that a physical name will be allocated by CloudFormation during deployment. - a concrete value implies a specific physical name -PhysicalName.GENERATE_IF_NEEDEDis a marker that indicates that a physical will only be generated by the CDK if it is needed for cross-environment references. Otherwise, it will be allocated by CloudFormation. Default: - The physical name will be allocated by CloudFormation at deployment timeregion (
Optional[str]) – The AWS region this resource belongs to. Default: - the resource is in the same region as the stack it belongs to
Methods
- 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 aprefixand/orsuffixthat 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
- Return type:
None
Example:
# my_lambda: lambda.Function bucket = s3.Bucket(self, "MyBucket") bucket.add_event_notification(s3.EventType.OBJECT_CREATED, s3n.LambdaDestination(my_lambda), prefix="home/myusername/*")
- 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.OBJECT_CREATED).- Parameters:
dest (
IBucketNotificationDestination) – The notification destination (see onEvent).filters (
NotificationKeyFilter) – Filters (see onEvent).
- 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.OBJECT_REMOVED).- Parameters:
dest (
IBucketNotificationDestination) – The notification destination (see onEvent).filters (
NotificationKeyFilter) – Filters (see onEvent).
- Return type:
None
- add_replication_policy(role_arn, access_control_transition=None, account=None)
Function to add required permissions to the destination bucket for cross account replication.
These permissions will be added as a resource based policy on the bucket
- Parameters:
role_arn (
str)access_control_transition (
Optional[bool])account (
Optional[str])
- See:
- 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 its contents. Use
bucketArnandarnForObjects(keys)to obtain ARNs for this bucket or objects.Note that the policy statement may or may not be added to the policy. For example, when an
IBucketis created from an existing bucket, it’s not possible to tell whether the bucket already has a policy attached, let alone to re-use that policy to add more statements to it. So it’s safest to do nothing in these cases.- Parameters:
permission (
PolicyStatement) – the policy statement to be added to the bucket’s policy.- Return type:
- Returns:
metadata about the execution of this method. If the policy was not added, the value of
statementAddedwill befalse. You should always check this value to make sure that the operation was actually carried out. Otherwise, synthesis and deploy will terminate silently, which may be confusing.
- apply_removal_policy(policy)
Apply the given removal policy to this resource.
The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you’ve removed it from the CDK application or because you’ve made a change that requires the resource to be replaced.
The resource can be deleted (
RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).- Parameters:
policy (
RemovalPolicy)- Return type:
None
- 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
- enable_event_bridge_notification()
Enables event bridge notification, causing all events below to be sent to EventBridge:. :rtype:
NoneObject Deleted (DeleteObject)
Object Deleted (Lifecycle expiration)
Object Restore Initiated
Object Restore Completed
Object Restore Expired
Object Storage Class Changed
Object Access Tier Changed
Object ACL Updated
Object Tags Added
Object Tags Deleted
- grant_delete(identity, objects_key_pattern=None)
Grants s3:DeleteObject* permission to an IAM principal for objects in this bucket.
- Parameters:
identity (
IGrantable) – The principal.objects_key_pattern (
Any) – Restrict the permission to a certain key pattern (default ‘*’). Parameter type isanybutstringshould be passed in.
- Return type:
- 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.Grantobject, 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” });Note that if this
IBucketrefers to an existing bucket, possibly not managed by CloudFormation, this method will have no effect, since it’s impossible to modify the policy of an existing bucket.- 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_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 (
Any) – Restrict the permission to a certain key pattern (default ‘*’). Parameter type isanybutstringshould be passed in.
- Return type:
- grant_put_acl(identity, objects_key_pattern=None)
Grant the given IAM identity permissions to modify the ACLs of objects in the given Bucket.
If your application has the ‘@aws-cdk/aws-s3:grantWriteWithoutAcl’ feature flag set, calling
grantWriteorgrantReadWriteno longer grants permissions to modify the ACLs of the objects; in this case, if you need to modify object ACLs, call this method explicitly.- Parameters:
identity (
IGrantable)objects_key_pattern (
Optional[str])
- Return type:
- 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 (
Any) – Restrict the permission to a certain key pattern (default ‘*’). Parameter type isanybutstringshould be passed in.
- Return type:
- 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.
Before CDK version 1.85.0, this method granted the
s3:PutObject*permission that includeds3:PutObjectAcl, which could be used to grant read/write object access to IAM principals in other accounts. If you want to get rid of that behavior, update your CDK version to 1.85.0 or later, and make sure the@aws-cdk/aws-s3:grantWriteWithoutAclfeature flag is set totruein thecontextkey of your cdk.json file. If you’ve already updated, but still need the principal to have permissions to modify the ACLs, use thegrantPutAclmethod.- Parameters:
identity (
IGrantable)objects_key_pattern (
Any)
- Return type:
- grant_replication_permission(identity, *, destinations, source_decryption_key=None)
Grant replication permission to a principal. This method allows the principal to perform replication operations on this bucket.
Note that when calling this function for source or destination buckets that support KMS encryption, you need to specify the KMS key for encryption and the KMS key for decryption, respectively.
- Parameters:
identity (
IGrantable) – The principal to grant replication permission to.destinations (
Sequence[Union[GrantReplicationPermissionDestinationProps,Dict[str,Any]]]) – The destination buckets for replication. Specify the KMS key to use for encryption if a destination bucket needs to be encrypted with a customer-managed KMS key. One or more destination buckets are required if replication configuration is enabled (i.e.,replicationRoleis specified). Default: - empty array (valid only if thereplicationRoleproperty is NOT specified)source_decryption_key (
Optional[IKey]) – The KMS key used to decrypt objects in the source bucket for replication. Required if the source bucket is encrypted with a customer-managed KMS key. Default: - it’s assumed the source bucket is not encrypted with a customer-managed KMS key.
- Return type:
- grant_write(identity, objects_key_pattern=None, allowed_action_patterns=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.
Before CDK version 1.85.0, this method granted the
s3:PutObject*permission that includeds3:PutObjectAcl, which could be used to grant read/write object access to IAM principals in other accounts. If you want to get rid of that behavior, update your CDK version to 1.85.0 or later, and make sure the@aws-cdk/aws-s3:grantWriteWithoutAclfeature flag is set totruein thecontextkey of your cdk.json file. If you’ve already updated, but still need the principal to have permissions to modify the ACLs, use thegrantPutAclmethod.- Parameters:
identity (
IGrantable)objects_key_pattern (
Any)allowed_action_patterns (
Optional[Sequence[str]])
- Return type:
- on_cloud_trail_event(id, *, paths=None, target=None, cross_stack_scope=None, description=None, event_pattern=None, rule_name=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[Sequence[str]]) – Only watch changes to these object paths. Default: - Watch changes to all objectstarget (
Optional[IRuleTarget]) – The target to register for the event. Default: - No target is added to the rule. UseaddTarget()to add a target.cross_stack_scope (
Optional[Construct]) – The scope to use if the source of the rule and its target are in different Stacks (but in the same account & region). This helps dealing with cycles that often arise in these situations. Default: - none (the main scope will be used, even for cross-stack Events)description (
Optional[str]) – A description of the rule’s purpose. Default: - No descriptionevent_pattern (
Union[EventPattern,Dict[str,Any],None]) – 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.
- Return type:
- on_cloud_trail_put_object(id, *, paths=None, target=None, cross_stack_scope=None, description=None, event_pattern=None, rule_name=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 cpwill automatically use either PutObject or the multipart upload API depending on the file size, so usingonCloudTrailWriteObjectmay 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[Sequence[str]]) – Only watch changes to these object paths. Default: - Watch changes to all objectstarget (
Optional[IRuleTarget]) – The target to register for the event. Default: - No target is added to the rule. UseaddTarget()to add a target.cross_stack_scope (
Optional[Construct]) – The scope to use if the source of the rule and its target are in different Stacks (but in the same account & region). This helps dealing with cycles that often arise in these situations. Default: - none (the main scope will be used, even for cross-stack Events)description (
Optional[str]) – A description of the rule’s purpose. Default: - No descriptionevent_pattern (
Union[EventPattern,Dict[str,Any],None]) – 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.
- Return type:
- on_cloud_trail_write_object(id, *, paths=None, target=None, cross_stack_scope=None, description=None, event_pattern=None, rule_name=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 cpwill automatically use either PutObject or the multipart upload API depending on the file size, so using this method may be preferable toonCloudTrailPutObject.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[Sequence[str]]) – Only watch changes to these object paths. Default: - Watch changes to all objectstarget (
Optional[IRuleTarget]) – The target to register for the event. Default: - No target is added to the rule. UseaddTarget()to add a target.cross_stack_scope (
Optional[Construct]) – The scope to use if the source of the rule and its target are in different Stacks (but in the same account & region). This helps dealing with cycles that often arise in these situations. Default: - none (the main scope will be used, even for cross-stack Events)description (
Optional[str]) – A description of the rule’s purpose. Default: - No descriptionevent_pattern (
Union[EventPattern,Dict[str,Any],None]) – 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.
- Return type:
- s3_url_for_object(key=None)
The S3 URL of an S3 object. For example:.
s3://onlybuckets3://bucket/key
- 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
- to_string()
Returns a string representation of this construct.
- Return type:
str
- transfer_acceleration_url_for_object(key=None, *, dual_stack=None)
The https Transfer Acceleration URL of an S3 object.
Specify
dualStack: trueat the options for dual-stack endpoint (connect to the bucket over IPv6). For example:https://bucket---s3-accelerate.amazonaws.com.rproxy.govskope.cahttps://bucket.s3-accelerate.amazonaws.com/key
- Parameters:
key (
Optional[str]) – The S3 key of the object. If not specified, the URL of the bucket is returned.dual_stack (
Optional[bool]) – Dual-stack support to connect to the bucket over IPv6. Default: - false
- Return type:
str- Returns:
an TransferAccelerationUrl token
- url_for_object(key=None)
The https URL of an S3 object. Specify
regional: falseat the options for non-regional URLs. For example:.https://s3.us-west-1.amazonaws.com/onlybuckethttps://s3.us-west-1.amazonaws.com/bucket/keyhttps://s3---cn-north-1.amazonaws.com.rproxy.govskope.ca.cn/china-bucket/mykey
- 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
- virtual_hosted_url_for_object(key=None, *, regional=None)
The virtual hosted-style URL of an S3 object. Specify
regional: falseat the options for non-regional URL. For example:.https://only-bucket---s3---us-west-1.amazonaws.com.rproxy.govskope.cahttps://bucket.s3.us-west-1.amazonaws.com/keyhttps://bucket.s3.amazonaws.com/keyhttps://china-bucket---s3---cn-north-1.amazonaws.com.rproxy.govskope.ca.cn/mykey
- 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
Attributes
- bucket_arn
The ARN of the bucket.
- bucket_domain_name
The IPv4 DNS name of the specified bucket.
- bucket_dual_stack_domain_name
The IPv6 DNS name of the specified bucket.
- bucket_name
The name of the bucket.
- bucket_ref
A reference to a Bucket resource.
- bucket_regional_domain_name
The regional domain name of the specified bucket.
- bucket_website_domain_name
The Domain name of the static website.
- bucket_website_url
The URL of the static website.
- encryption_key
Optional KMS encryption key associated with this bucket.
- 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.
- is_website
If this bucket has been configured for static website hosting.
- node
The tree node.
- policy
The resource policy associated with this bucket.
If
autoCreatePolicyis true, aBucketPolicywill be created upon the first call to addToResourcePolicy(s).
- replication_role_arn
Role used to set up permissions on this bucket for replication.
- stack
The stack in which this resource is defined.
Static Methods
- classmethod is_construct(x)
Checks if
xis a construct.Use this method instead of
instanceofto properly detectConstructinstances, even when the construct library is symlinked.Explanation: in JavaScript, multiple copies of the
constructslibrary on disk are seen as independent, completely different libraries. As a consequence, the classConstructin each copy of theconstructslibrary is seen as a different class, and an instance of one class will not test asinstanceofthe other class.npm installwill not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of theconstructslibrary can be accidentally installed, andinstanceofwill behave unpredictably. It is safest to avoid usinginstanceof, and using this type-testing method instead.- Parameters:
x (
Any) – Any object.- Return type:
bool- Returns:
true if
xis an object created from a class which extendsConstruct.
- classmethod is_owned_resource(construct)
Returns true if the construct was created by CDK, and false otherwise.
- Parameters:
construct (
IConstruct)- Return type:
bool
- classmethod is_resource(construct)
Check whether the given construct is a Resource.
- Parameters:
construct (
IConstruct)- Return type:
bool