Sub topic 5
Defining resources: an S3 bucket and a Lambda function
This chapter assumes you know what S3 and Lambda do, can read TypeScript or Python, and have a CDK project from the setup chapter. You will define a bucket and a function in one stack.
The shape of every resource
Every L2 construct is created the same way: new Type(scope, id, props).
scopeis the parent construct, usuallythisinside a stack.idis a name that is unique within that scope. CDK uses it to build the logical ID in the CloudFormation template.propsis an object of settings. Most are optional because L2 constructs supply defaults.
Changing an id later changes the logical ID, so CloudFormation treats it as a new resource and may replace the old one. Choose ids carefully before the first deploy.
A bucket and a function
The stack below creates a versioned bucket and a Lambda function. It passes the bucket name to the function as an environment variable.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as lambda from 'aws-cdk-lib/aws-lambda';
export class AppStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const bucket = new s3.Bucket(this, 'UploadsBucket', {
versioned: true,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
const fn = new lambda.Function(this, 'Processor', {
runtime: lambda.Runtime.NODEJS_20_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('lambda'),
environment: { BUCKET_NAME: bucket.bucketName },
});
bucket.grantRead(fn);
}
}
const app = new cdk.App();
new AppStack(app, 'AppStack', {
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION,
},
});The lambda directory must contain an index.js that exports handler. The Python version differs only in naming. It uses snake_case (removal_policy, bucket.bucket_name, grant_read) and imports aws_lambda as _lambda, because lambda is a reserved word in Python.
What the props do
| Prop | Effect |
|---|---|
| `versioned: true` | Turns on S3 versioning. |
| `removalPolicy: RETAIN` | Keeps the bucket if the stack is deleted. |
| `runtime` and `handler` | Select the language runtime and the entry function. |
| `code: fromAsset('lambda')` | Zips the local directory and uploads it during deploy. |
| `environment` | Sets environment variables on the function. |
How the references connect
bucket.bucketName is not a string you can print during synthesis. It is a token that CloudFormation fills in at deploy time. Passing it to another construct creates a dependency, so the bucket is created first.
Common errors
- Missing asset directory:
fromAsset('lambda')fails at synth if the path does not exist. The path is relative to where you runcdk. - Duplicate ids: two constructs with the same id in one scope throw an error.
- Hard-coded names: setting
bucketNameyourself can collide across accounts. Let CDK generate names unless you need a fixed one.
Exercise
You rename the bucket's id from 'UploadsBucket' to 'FilesBucket' and run cdk deploy. What does cdk diff show, and why does it matter for a bucket with RETAIN?
Show answer
The diff shows a new bucket added and the old one removed, because the id determines the logical ID. With RETAIN the old bucket is kept, but it is no longer managed by the stack and its data is not copied to the new bucket.