Sub topic 5
L1, L2 and L3 constructs
This chapter assumes you have read the previous chapter on apps, stacks and the construct tree. You should be able to write a basic stack in TypeScript or Python and know that every resource lives somewhere in a tree of constructs.
Every resource in a CDK app is a construct. Constructs come in three levels, and the level decides how much the library does for you and how closely your code matches the CloudFormation template.
The three levels
| Level | Also called | Naming | What it gives you |
|---|---|---|---|
| L1 | CFN resources | `Cfn` prefix, such as `s3.CfnBucket` | A one-to-one mapping to a CloudFormation resource type. No defaults, no helpers. |
| L2 | Curated constructs | Plain name, such as `s3.Bucket` | Sensible defaults, typed enums, helper methods and grant methods. |
| L3 | Patterns | Descriptive name, such as `ApplicationLoadBalancedFargateService` | Several resources wired together for a common architecture. |
The levels are not separate systems. An L2 construct creates an L1 construct inside itself, and an L3 pattern creates L2 constructs. Only L1 constructs produce CloudFormation resources directly.
L1: CloudFormation, expressed in code
L1 constructs are generated from the CloudFormation resource specification. Each property in the CloudFormation reference exists on the L1 class, with the name converted to camelCase (or snake_case in Python). Because they are generated, they appear as soon as CloudFormation supports a new resource or property, and they have no behavior of their own.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
export class RawStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
new s3.CfnBucket(this, 'RawBucket', {
versioningConfiguration: { status: 'Enabled' },
publicAccessBlockConfiguration: {
blockPublicAcls: true,
blockPublicPolicy: true,
ignorePublicAcls: true,
restrictPublicBuckets: true,
},
});
}
}The Python equivalent uses keyword arguments and nested property classes:
from aws_cdk import Stack
from aws_cdk import aws_s3 as s3
from constructs import Construct
class RawStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
s3.CfnBucket(
self,
"RawBucket",
versioning_configuration=s3.CfnBucket.VersioningConfigurationProperty(
status="Enabled"
),
public_access_block_configuration=s3.CfnBucket.PublicAccessBlockConfigurationProperty(
block_public_acls=True,
block_public_policy=True,
ignore_public_acls=True,
restrict_public_buckets=True,
),
)Two things stand out. Status is the string 'Enabled', not an enum, because L1 types follow the CloudFormation schema. And every setting you omit is left to CloudFormation's own default, so the code states exactly what the template will say.
L1 gets harder with resources that need many collaborators. A CfnFunction requires an role ARN that you must create yourself, and its code property takes an inline zipFile or an S3 location. It does not bundle a local directory.
L2: the level you will use most
An L2 construct is a hand-written class that models one AWS resource, or a small cluster of closely related ones, as an object-oriented API. It adds four things:
- Defaults.
new s3.Bucket(this, 'B')needs no properties. - Typed options. Enums such as
s3.BucketEncryption.S3_MANAGEDreplace free-form strings. - Helper methods. Examples are
bucket.addLifecycleRule(...)andbucket.addEventNotification(...). - Grants and wiring.
bucket.grantRead(fn)creates the right IAM policy statements, as covered in the grants chapter.
The same bucket as the L1 example, written as L2:
new s3.Bucket(this, 'Bucket', {
versioned: true,
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
});One L2 construct may create several CloudFormation resources. A lambda.Function creates an AWS::Lambda::Function, an IAM role and its policies, and sometimes a log group or custom resource. You can see this by running cdk synth and comparing the template to your code. The mismatch between lines of code and template resources is the main reason to read the synthesized output while learning.
L3: patterns
An L3 construct, also called a pattern, assembles a whole architecture. It is opinionated: it decides which resources exist and how they connect.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as ecsPatterns from 'aws-cdk-lib/aws-ecs-patterns';
export class WebStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Web', {
desiredCount: 2,
taskImageOptions: {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
},
});
}
}With no cluster or VPC supplied, this one statement creates a VPC, an ECS cluster, a Fargate service, a task definition, an Application Load Balancer, a listener, security groups and IAM roles. The defaults are convenient but have cost and networking consequences, such as NAT gateways in a new VPC. Review cdk diff before you deploy a pattern for the first time.
Your own reusable constructs, such as the SecureBucket in a later chapter, are also L3 in spirit, even though the CDK does not enforce the label.
Escape hatches: moving between levels
When an L2 lacks a property that CloudFormation supports, you do not have to abandon it. Reach down to the L1 it created with node.defaultChild:
const bucket = new s3.Bucket(this, 'Bucket', { versioned: true });
const cfnBucket = bucket.node.defaultChild as s3.CfnBucket;
cfnBucket.accelerateConfiguration = { accelerationStatus: 'Enabled' };
// For a property the L1 class does not model yet, patch the template directly:
cfnBucket.addPropertyOverride('AnalyticsConfigurations.0.Id', 'weekly');addPropertyOverride and addOverride write raw values into the template and bypass type checking. Use them sparingly and leave a comment explaining why, because a typo is only caught at deploy time.
Choosing a level
Start at the highest level that fits, then drop down when it stops fitting.
- Use an L3 pattern when your architecture matches it and you accept its decisions.
- Use L2 for most work. It gives you grants, defaults and validation.
- Use L1 when no L2 exists, for example for a newly released service, or when you need exact control of every template property.
- Use an escape hatch when an L2 is almost right and missing one property.
Some L2 modules are published separately as -alpha packages. Their APIs can change between releases, so pin versions and read the release notes before upgrading.
Exercise
A teammate writes new s3.CfnBucket(this, 'Data', { bucketName: 'data' }) and then tries to call .grantRead(fn) on it. Why does this fail, and what are two ways to fix it?
Show answer
Grant methods exist only on L2 constructs. An L1 CfnBucket is a plain mapping of the CloudFormation resource and has no helper methods. One fix is to replace it with an L2 s3.Bucket, which has grantRead. The other is to keep the L1 and write the IAM policy statement by hand, for example with fn.addToRolePolicy, granting s3:GetObject on the bucket's ARN. The first option is preferred because the grant method generates the correct actions and resource ARNs.
Exercise
You run cdk synth on a stack containing one lambda.Function and see more than one resource in the template. Which level explains this, and what extra resource is almost always present?
Show answer
The L2 level explains it. An L2 construct can create several L1 resources. The extra resource is the IAM execution role for the function, plus any policies attached to it.