AWS CDK S3 Assets

1.204.0 · maintenance · verified Thu Apr 16

This AWS CDK v1 construct allows you to deploy local files or directories to an Amazon S3 bucket. It handles packaging (e.g., zipping) and uploading the assets, making them available for other CDK constructs or applications. As part of AWS CDK v1, it is currently in maintenance mode, with v2 being the active major version. The latest v1 release is 1.204.0.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create an `Asset` from a local directory. It creates a temporary folder, adds a file, defines a CDK stack that uses `Asset` to reference this folder, and outputs the S3 details. To run, save as `app.py`, then execute `cdk synth` in the same directory. This generates the CloudFormation template.

import os
import aws_cdk as core
from aws_cdk.aws_s3_assets import Asset

# Create a dummy local directory and file for the asset
asset_dir = 'my_local_asset_folder'
if not os.path.exists(asset_dir):
    os.makedirs(asset_dir)
with open(os.path.join(asset_dir, 'hello.txt'), 'w') as f:
    f.write('Hello, CDK S3 Assets v1!')

class MyAssetStack(core.Stack):
    def __init__(self, scope: core.App, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Create an S3 Asset from the local folder
        my_asset = Asset(self, 'MyWebsiteAsset',
                         path=asset_dir,
                         packaging=core.BundlingFileAccess.BUNDLE_IMAGE  # Use BUNDLE_IMAGE to ensure directory content is bundled
                        )

        # Output the S3 URL of the deployed asset
        core.CfnOutput(self, 'AssetBucketName', value=my_asset.s3_bucket_name)
        core.CfnOutput(self, 'AssetObjectKey', value=my_asset.s3_object_key)
        core.CfnOutput(self, 'AssetHttpUrl', value=f"https://{my_asset.s3_bucket_name}.s3.amazonaws.com/{my_asset.s3_object_key}")

app = core.App()
MyAssetStack(app, "S3AssetQuickstartStack")
app.synth()

# Clean up the dummy directory
import shutil
shutil.rmtree(asset_dir)

view raw JSON →