Sub topic 2
Defining Resources with the AWS CDK
Assume you know basic S3, Lambda, and IAM concepts, can use a terminal, and have Node.js and configured AWS credentials. This chapter uses TypeScript. The same CDK model works in Python.
Define an S3 bucket and Lambda function
The AWS Cloud Development Kit (CDK) represents infrastructure as a construct tree. A stack contains resources that CDK synthesizes into an AWS CloudFormation template.
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 processor = 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(processor);
}
}Bucket and Function are level 2 constructs They provide sensible defaults and helper methods. versioned keeps older object versions. RETAIN prevents stack deletion from deleting the bucket.
Grant permissions with resource methods
grantRead(processor) adds an IAM policy to the Lambda execution role. The function can read objects from this bucket without you writing resource ARNs or policy statements manually. Use the narrowest grant that meets the requirement, such as grantRead, grantWrite, or grantReadWrite.
Understand tokens
bucket.bucketName is usually a CDK token. The bucket name does not exist while TypeScript runs because CloudFormation creates the bucket later. CDK places a reference in the synthesized template, and CloudFormation resolves it during deployment.
Choose an environment and bootstrap it
An environment is an AWS account and Region. Make the target explicit when deploying:
const app = new cdk.App();
new AppStack(app, "AppStack", {
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION,
},
});Bootstrap an account and Region once before deployments that require CDK assets:
cdk bootstrap aws://123456789012/us-east-1Synthesize, review, deploy, and destroy
cdk synth
cdk diff
cdk deploy
cdk destroycdk synth generates CloudFormation. cdk diff compares the proposed template with the deployed stack. Review the diff before cdk deploy. Destroy removes the stack, but retained resources such as this bucket remain.
Exercise
Why can the Lambda environment contain bucket.bucketName before the bucket exists?
Show answer
The value is a CDK token that becomes a CloudFormation reference and resolves during deployment.