Sub topic 12
Assets: bundling Lambda code and files
This chapter covers how the CDK moves local files, such as Lambda source code, into your AWS account. It assumes you know how to define a stack and a Lambda function, and that you have bootstrapped your environment.
What an asset is
An asset is a local file or directory that your CDK app needs at deploy time. CloudFormation templates cannot contain a whole code folder. The template can only point to a location, such as an S3 object. The CDK solves this by packaging the file, uploading it to a bootstrapped location, and writing that location into the template.
You have already used an asset. In the earlier Lambda example, this line created one:
code: lambda.Code.fromAsset('lambda'),The CDK packs the lambda directory into a zip file during synthesis. During deployment it uploads the zip to the bootstrap bucket, then references the object in the Lambda resource.
How assets flow through the pipeline
Assets touch three phases: synthesis, publishing and deployment.
- Synthesis. The CDK copies or zips the source into the
cdk.outdirectory. It computes a hash of the contents and uses that hash in the file name. - Publishing. During
cdk deploy, the CLI uploads the file to the S3 bucket created by bootstrapping. Docker image assets go to an ECR repository instead. - Deployment. CloudFormation receives a template whose resource properties point to the uploaded object.
Because the file name contains a content hash, the template changes only when your code changes. If you edit nothing, cdk diff shows no difference and the deploy does not touch the function.
Why bootstrapping matters
Assets need somewhere to go. The bootstrap stack creates the staging bucket and image repository, plus the roles the CLI uses to publish to them. If you deploy a stack with assets to an environment that was never bootstrapped, the deploy fails. The error usually mentions a missing bootstrap stack or a missing bucket. Run cdk bootstrap for that account and region and retry.
File and directory assets
Use Asset from aws-cdk-lib/aws-s3-assets when you need a file in S3 that is not Lambda code. The asset exposes properties you can pass to other resources.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as path from 'path';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as assets from 'aws-cdk-lib/aws-s3-assets';
export class ConfigStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const configAsset = new assets.Asset(this, 'ConfigFile', {
path: path.join(__dirname, '..', 'assets', 'config.json'),
});
const role = new iam.Role(this, 'ReaderRole', {
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
});
configAsset.grantRead(role);
new cdk.CfnOutput(this, 'ConfigUri', { value: configAsset.s3ObjectUrl });
}
}The values s3ObjectUrl, bucket and s3ObjectKey are tokens. They resolve at deploy time, so you cannot print them during synthesis. The grantRead method gives the role access to the staged object, the same pattern you used for buckets.
The same class works in Python as aws_cdk.aws_s3_assets.Asset, with path and grant_read in snake_case.
Resolve paths reliably
A relative path such as 'lambda' is resolved against the current working directory, not the file that contains it. If you run cdk from a different folder, the asset may not be found. Build paths from the source file's location instead:
- TypeScript:
path.join(__dirname, '..', 'lambda') - Python:
os.path.join(os.path.dirname(__file__), "..", "lambda")
Bundling: building code before packaging
Many functions need a build step: compiling TypeScript, installing dependencies, or packaging a Python library. Bundling runs that step during synthesis. There are three common approaches.
| Approach | How it works | Trade-off |
|---|---|---|
| `Code.fromAsset` on a prepared folder | You build the folder yourself before `cdk synth` | Simple, but a manual step you can forget |
| `NodejsFunction` (`aws-cdk-lib/aws-lambda-nodejs`) | Bundles with esbuild, locally if esbuild is installed, otherwise in Docker | Fast for Node.js, small output |
| `PythonFunction` (`@aws-cdk/aws-lambda-python-alpha`) | Installs `requirements.txt` in Docker | Needs Docker, and the module is experimental |
A NodejsFunction example:
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import * as lambda from 'aws-cdk-lib/aws-lambda';
const fn = new NodejsFunction(this, 'Handler', {
entry: path.join(__dirname, '..', 'src', 'handler.ts'),
handler: 'handler',
runtime: lambda.Runtime.NODEJS_20_X,
});For full control, pass a bundling option to Code.fromAsset. It runs a command inside a Docker image and treats the output directory as the asset. You can also supply local bundling, which tries a command on your machine first and falls back to Docker.
Excluding files and controlling the hash
Assets include everything in the directory by default, including node_modules, test files and .git data if present. Large or noisy folders slow synthesis and can change the hash for irrelevant reasons.
- Use the
excludeoption with glob patterns to leave files out. - Keep Lambda source in a dedicated folder rather than pointing at the project root.
- Remember that any change inside the folder, even a comment, produces a new hash and a new deployment of the function.
Docker image assets
If a function runs as a container image, use DockerImageCode.fromImageAsset with a directory that holds a Dockerfile. The CDK builds the image during cdk deploy, pushes it to the bootstrap ECR repository, and references it by digest. Docker must be running on the machine that deploys.
Common errors
- Cannot find asset path. The path is wrong or relative to the wrong directory. Use
__dirnameor__file__. - Docker not running. Bundling or image assets need a Docker daemon. Start it or use local bundling.
- Bootstrap version too old. Newer features need a current bootstrap stack. Re-run
cdk bootstrap. - Unexpected redeploys. Generated files, such as build output or timestamps, sit inside the asset directory. Exclude them.
- Size limits. A Lambda zip package is limited to 50 MB, and 250 MB unzipped. Large dependencies belong in layers or container images.
Summary of the model
An asset turns a local path into a content-hashed object that the template can reference. The CDK handles zipping, uploading and wiring the reference. You are responsible for choosing stable paths, building code before packaging, and keeping unneeded files out of the folder.
Exercise
You change only a README file inside the directory passed to Code.fromAsset('lambda'), then run cdk diff. What do you expect to see, and how would you prevent it?
Show answer
The diff shows a changed asset hash and an updated Lambda code reference, because the hash covers every file in the directory. To prevent it, add the README to the exclude option, or move the Lambda source into a folder that contains only the files the function needs.
Exercise
A deploy fails with a message that the staging bucket does not exist. Which command fixes it, and why?
Show answer
Run cdk bootstrap aws://ACCOUNT/REGION for the target environment. Bootstrapping creates the S3 bucket and ECR repository where the CLI publishes assets, so a stack with assets cannot deploy until they exist.