Sub topic 15
Building your own construct
This chapter assumes you can define an S3 bucket and a Lambda function in a stack. It also assumes you know the difference between L1, L2 and L3 constructs, and that you know what a token is. Here you will package a pattern you repeat into a reusable construct.
Why write a construct
Say every bucket in your organization must be encrypted, block public access, and require TLS. You could copy those four properties into every stack, and sooner or later someone would forget one. A custom construct captures the rule once. Teams then use SecureBucket and get the defaults without remembering them.
A custom construct is an L3 construct, also called a pattern. It is an ordinary class that extends Construct and creates other constructs inside itself. It adds no new CloudFormation capability. It only groups and configures resources that already exist.
The anatomy of a construct
Every construct has the same constructor shape: a scope (the parent), an id (unique among siblings), and optional props.
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
export interface SecureBucketProps {
readonly versioned?: boolean;
}
export class SecureBucket extends Construct {
public readonly bucket: s3.Bucket;
constructor(scope: Construct, id: string, props: SecureBucketProps = {}) {
super(scope, id);
this.bucket = new s3.Bucket(this, 'Bucket', {
versioned: props.versioned ?? true,
encryption: s3.BucketEncryption.S3_MANAGED,
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
enforceSSL: true,
});
}
}Four conventions in this class are worth copying:
- A props interface with
readonlyfields. Mark optional fields with?and apply defaults inside the constructor, asprops.versioned ?? truedoes. - A default for the whole props object (
= {}) when every field is optional, so callers can writenew SecureBucket(this, 'Uploads'). - Child constructs use
thisas their scope. The newBucketbecomes a child ofSecureBucket, not of the stack. - Public readonly properties expose the inner resources. Callers can pass
secure.bucketto grant methods, event sources, or other constructs.
Composing larger patterns
Constructs can contain other custom constructs. This one combines SecureBucket with a Lambda function and connects them with a grant.
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { SecureBucket } from './secure-bucket';
export interface UploadProcessorProps {
/** Directory containing the Lambda source code. */
readonly codePath: string;
readonly versioned?: boolean;
}
export class UploadProcessor extends Construct {
public readonly uploads: s3.Bucket;
public readonly handler: lambda.Function;
constructor(scope: Construct, id: string, props: UploadProcessorProps) {
super(scope, id);
if (props.codePath.trim() === '') {
throw new Error('UploadProcessor: codePath must not be empty');
}
const secure = new SecureBucket(this, 'Uploads', {
versioned: props.versioned,
});
this.uploads = secure.bucket;
this.handler = new lambda.Function(this, 'Handler', {
runtime: lambda.Runtime.NODEJS_20_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(props.codePath),
environment: { BUCKET_NAME: this.uploads.bucketName },
});
this.uploads.grantRead(this.handler);
}
}A stack then needs one line: new UploadProcessor(this, 'Processor', { codePath: 'lambda' });.
The construct tree now has more levels. Each level adds to the path that CDK uses to build logical IDs.
Design rules for reusable constructs
Keep the following rules in mind as you write constructs for others to use.
- Expose resources, not copies of their settings. A public
bucketproperty is more flexible than re-declaringbucketNameandbucketArnon your construct. - Keep props small. Offer the few settings that legitimately vary. If callers need every bucket option, they should use
s3.Bucketdirectly. - Validate early. Throw an
Errorin the constructor for invalid combinations, as thecodePathcheck does. For checks that must see the final tree, usethis.node.addValidation(), which runs at synthesis. - Avoid physical names. Do not set
bucketNameorfunctionName. A fixed name blocks replacement updates and prevents deploying the construct twice in one account and region. - Do not read environment variables or call AWS inside the constructor. Pass values in through props so the construct stays deterministic and testable.
- Do not branch on tokens. A value such as
bucket.bucketNameis a placeholder at synthesis time. Anifon it compares the placeholder text, not the real name. Usecdk.Fn.conditionIfor a CloudFormation condition for deploy-time decisions.
Constructs and logical IDs
CloudFormation identifies a resource by its logical ID, and the CDK derives it from the construct path plus a hash. Wrapping an existing resource in a new construct changes its path. After the next deploy, CloudFormation sees a new logical ID and replaces the resource. For a stateful resource such as a database or a bucket with data, replacement can mean data loss.
Testing a construct
You can test a construct by putting it in a throwaway stack. Synthesizing happens in memory, so no AWS access is needed.
import * as cdk from 'aws-cdk-lib';
import { Template } from 'aws-cdk-lib/assertions';
import { SecureBucket } from '../lib/secure-bucket';
test('SecureBucket blocks public access and encrypts', () => {
const stack = new cdk.Stack(new cdk.App(), 'TestStack');
new SecureBucket(stack, 'Uploads');
const template = Template.fromStack(stack);
template.hasResourceProperties('AWS::S3::Bucket', {
PublicAccessBlockConfiguration: { BlockPublicAcls: true },
VersioningConfiguration: { Status: 'Enabled' },
});
});Test the defaults and each prop that changes the output. A test that asserts the secure defaults protects your organization's rules when someone later edits the construct.
Sharing constructs
A construct in one repository can be imported by relative path. To share it more widely, publish it as a package (npm for TypeScript, PyPI for Python) and version it with semantic versioning. Adding an optional prop is a minor change. Removing a prop, or altering defaults in a way that changes resources, is a breaking change, because consumers' deployments would be modified by an upgrade.
Exercise
You wrap an existing deployed s3.Bucket (id Uploads, directly in the stack) into a new SecureBucket construct that creates the bucket with the id Bucket. cdk diff shows the bucket will be replaced. Why does this happen, and what should you check or do before deploying?
Show answer
Moving the bucket under a new parent changes its construct path (from Uploads to Uploads/Bucket/... or similar), so the CDK generates a different logical ID. CloudFormation treats it as a new resource and deletes the old one. Before deploying, confirm the bucket holds no data you need and set RemovalPolicy.RETAIN. Better, keep the original logical ID by calling overrideLogicalId on the underlying CfnBucket (bucket.node.defaultChild), then run cdk diff again to confirm there is no replacement.