Constructs come in different levels which can help identify the level of complexity and ease of use of a construct.
| L1 (CloudFormation Level 1) Constructs: |
|---|
![]() |
| L2 (CloudFormation Level 2) Constructs: |
|---|
![]() |
| L3 (CloudFormation Level 3) Patterns and Higher-level Constructs: |
|---|
![]() |
To further drive home this point here’s a comparison of what you write as IaC (Infrastructure as Code) and what it looks like in CloudFormation:
(!) It’s important to note that if you are following along or testing these commands out on the lifecycle-devops account, you do not accidentally run “npm publish” as this can potentially publish your lesson library to codeartifact i lifecycle-devops directly.
This is a level 1 construct written in Typescript:
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { Construct } from 'constructs';
export class L1LambdaConstruct extends Construct {
constructor(scope: Construct, id: string) {
super(scope, id);
new lambda.CfnFunction(this, 'MySimpleFunction', {
runtime: 'nodejs14.x',
handler: 'index.handler',
code: {
s3Bucket: 'my-bucket',
s3Key: 'code/my-lambda.zip'
},
role: 'arn:aws:iam::account-id:role/execution_role'
});
}
}
And this is the resulting cloudformation that is created from the above level 1 construct:
Resources:
MySimpleFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: nodejs14.x
Handler: index.handler
Code:
S3Bucket: my-bucket
S3Key: code/my-lambda.zip
Role: arn:aws:iam::account-id:role/execution_role
Outputs:
LambdaFunctionArn:
Description: "Lambda Function ARN"
Value: !GetAtt MySimpleFunction.Arn
And this is a level 2 Construct written in Typescript:
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { Construct } from 'constructs';
export class L2LambdaConstruct extends Construct {
constructor(scope: Construct, id: string) {
super(scope, id);
new lambda.Function(this, 'MySimpleFunction', {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('lambda-code-directory')
});
}
}