Sub topic 6
Defining resources: an S3 bucket and a Lambda function
This chapter assumes you have a CDK project from the setup chapter. It also assumes you know what an App, a Stack and the construct tree are, and that you can read basic S3, Lambda and IAM terms. You will define a versioned bucket and a Lambda function that reads from it, first in TypeScript and then in Python.
The shape of every resource definition
Every L2 construct (the higher-level, resource-specific classes) takes the same three arguments:
scope: the parent construct. Inside a stack's constructor this isthis.id: a string that names the construct within its parent. It must be unique among siblings.props: an object of options. Anything you leave out gets a default.
The id matters more than it looks. CDK uses the path of ids through the tree to build the logical ID of the CloudFormation resource. If you rename an id after deploying, CloudFormation sees a new resource. It creates the new one and deletes the old one. For a bucket or a database, that can destroy data.
The stack
The following stack defines a bucket and a function, and lets the function read the bucket.
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 Python version uses the same model. Only the naming conventions change: snake_case for properties and methods, and an underscore suffix on aws_lambda because lambda is a reserved word.
from aws_cdk import App, Environment, RemovalPolicy, Stack
from aws_cdk import aws_lambda as _lambda
from aws_cdk import aws_s3 as s3
from constructs import Construct
import os
class AppStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
bucket = s3.Bucket(
self,
"UploadsBucket",
versioned=True,
removal_policy=RemovalPolicy.RETAIN,
)
fn = _lambda.Function(
self,
"Processor",
runtime=_lambda.Runtime.PYTHON_3_12,
handler="index.handler",
code=_lambda.Code.from_asset("lambda"),
environment={"BUCKET_NAME": bucket.bucket_name},
)
bucket.grant_read(fn)
app = App()
AppStack(
app,
"AppStack",
env=Environment(
account=os.environ.get("CDK_DEFAULT_ACCOUNT"),
region=os.environ.get("CDK_DEFAULT_REGION"),
),
)
app.synth()Both examples expect a lambda directory next to the CDK app, containing a file such as index.js or index.py that exports handler. Without it, synthesis fails because the asset path does not exist.
Props and defaults
An L2 construct is opinionated. When you write new s3.Bucket(this, 'UploadsBucket', { versioned: true }), you set one option and CDK chooses the rest. It generates a bucket name, which is why you rarely need to pick a globally unique one. It also applies default encryption and keeps the bucket private.
Some defaults protect you and some surprise you:
| Prop | Default behavior | Why you might change it |
|---|---|---|
| `bucketName` | Generated by CloudFormation | Set it only if something outside the stack needs a fixed name. A fixed name blocks replacement updates. |
| `removalPolicy` | `RETAIN` for the bucket resource | Set `DESTROY` for throwaway environments, and combine it with `autoDeleteObjects`. |
| `memorySize` (Lambda) | 128 MB | Raise it for CPU-heavy work, since CPU scales with memory. |
| `timeout` (Lambda) | 3 seconds | Raise it for anything that calls other services. |
The Lambda timeout is a common first error. A function that works in a quick test then fails in practice because three seconds is not enough.
Props are typed, so your editor lists the available options. Passing a wrong type fails at compile time in TypeScript. Passing a wrong value, such as an unsupported runtime for a given feature, fails later at synth or deploy time.
What the construct actually creates
Declaring two constructs does not produce two CloudFormation resources. The L2 Function creates the function and also an IAM execution role. The grantRead call adds a policy to that role. You can see this by synthesizing.
cdk synthIn the output template you will find AWS::S3::Bucket, AWS::Lambda::Function, AWS::IAM::Role and AWS::IAM::Policy. The policy lists read actions such as s3:GetObject and s3:ListBucket, scoped to this bucket's ARN. You wrote one line, and CDK wrote the rest.
Passing the bucket name to the function
The environment prop sets BUCKET_NAME on the function. The value bucket.bucketName is not a plain string at synth time, because CDK does not know the generated name yet. It is a token that CloudFormation resolves during deployment. The tokens chapter covers this in detail. For now, remember two rules: pass the property directly into other props, and do not try to log it, parse it or compare it in your code.
Referencing one construct's property from another also gives CloudFormation the dependency order. The function is created after the bucket, and you did not write a dependsOn.
Removal policy on the bucket
The examples set RETAIN explicitly. If you delete the stack, the bucket stays in your account with its objects. This is the safe choice for data you care about. Its cost is that a later redeploy with the same fixed bucket name fails, because the old bucket still owns the name. Letting CDK generate the name avoids this.
For a development stack you can opt in to cleanup:
const scratch = new s3.Bucket(this, 'ScratchBucket', {
removalPolicy: cdk.RemovalPolicy.DESTROY,
autoDeleteObjects: true,
});CloudFormation cannot delete a non-empty bucket. autoDeleteObjects adds a custom resource that empties the bucket first.
Common errors
- Asset path not found.
Code.fromAsset('lambda')is resolved relative to where you run the CDK command, so runcdk synthfrom the project root. - Handler mismatch.
index.handlermeans fileindex, exported functionhandler. A different filename gives a runtime error, not a deploy error. - Missing permission. Reading works through
grantRead, but writing needsgrantWriteorgrantReadWrite. AnAccessDeniedat runtime usually means the grant is missing or too narrow. - Environment not set. Without
env, the stack is environment-agnostic. That is fine until you use a feature that needs an account or region, such as a lookup.
Exercise
You rename the construct id 'UploadsBucket' to 'UserUploads' in a stack that is already deployed, with RemovalPolicy.RETAIN set. What will cdk diff show, and what happens to the old bucket if you deploy?
Show answer
The diff shows a new AWS::S3::Bucket being added and the old one being removed, because the changed id produces a new logical ID. On deploy, CloudFormation creates the new, empty bucket and removes the old resource from the stack. Because of RETAIN, the old bucket and its objects stay in the account but are no longer managed by the stack. Your function would point at the new, empty bucket.
Exercise
Your function calls s3:PutObject on the bucket and fails with AccessDenied, although the stack deploys cleanly. Which one-line change fixes it, and why did the deploy not catch the problem?
Show answer
Replace bucket.grantRead(fn) with bucket.grantReadWrite(fn), or add bucket.grantWrite(fn). The deploy succeeds because the policy is valid. It only grants read actions, and CloudFormation does not check what your code does at runtime.