Skip to Content
Cloud Engineering Academy
10. Infrastructure as Code

CDK constructs: L1, L2 and L3

Tell raw L1 resources from opinionated L2 constructs and L3 patterns, use grants and escape hatches, enforce rules with an aspect, and write your own EvidenceBucket construct that application teams can reuse from a NuGet package.

intermediate⏱ 2 h 30 min🟢 FreeDOP-C02SAP-C03

Assumes: .NET 10 LTS · Amazon.CDK.Lib 2.277.0 · AWS CDK CLI v2 · Node.js 22 LTS. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Explain the three construct levels (L1, L2, L3) and pick the right one for a task.
  • Read an L1 Cfn* construct and map every property to the CloudFormation reference.
  • Use grants (GrantRead, GrantPut) instead of hand-written IAM policies, and say what they generate.
  • Use the escape hatches (Node.DefaultChild, AddPropertyOverride, CfnOptions) when an L2 lacks a property.
  • Write a custom L3 construct (EvidenceBucket) with a typed props record, and package it for reuse.
  • Write an Aspect that checks every construct in the tree during synthesis.
  • Compare constructs with Terraform modules.

Prerequisites

Why this matters in banking

A bank with 60 application teams cannot have 60 slightly different versions of "an encrypted bucket". Some will forget TLS enforcement, some will pick a different key policy, and the auditor will sample the wrong ones. If the platform team publishes one construct that is the only sanctioned way to make an evidence bucket, the controls become a code review of one class, plus a test that fails if the class regresses. Teams still have freedom (names, retention, who can read) but cannot opt out of the controls by omission.

The same idea explains why you need to know the levels. At L1 nothing is defaulted, so a missing property is a missing control. At L2 and L3, defaults carry the policy, but you must know what they are.

The idea in plain language

A CDK construct is a class that adds resources to the tree. Constructs come in three levels:

LevelNameWhat it isExampleYou choose
L1CFN resourcesA 1:1 wrapper of a CloudFormation resource, generated from the CloudFormation specificationCfnBucket, CfnKeyEvery property, exactly as in CloudFormation
L2Curated constructsA hand-written class with a friendly API, defaults and helper methodsBucket, Key, RoleThe intent; defaults fill the rest
L3PatternsA construct that creates several resources working togetherApplicationLoadBalancedFargateService, your own EvidenceBucketA few high-level options

Analogy: L1 is a box of raw bricks, with a drawing for every brick. L2 is a prefabricated wall: you say "load-bearing, 3 metres" and it arrives with the right fixings. L3 is a prefabricated room: walls, door, window and wiring, ordered as "bathroom".

You can mix levels in one stack, and use L1 under an L2 when an L2 is missing a property.

What problem the three levels solve

  • L1 guarantees you can use any CloudFormation feature on the day it ships (L1 classes are generated from the specification), at the price of verbosity and no defaults.
  • L2 gives secure, readable code, and generates IAM policies from intent (grants).
  • L3 captures an organisation's pattern so it can be reused and reviewed once.

Honest limits

  • L2 defaults change over time (through feature flags), and the L2 may not expose every property. Always read the synthesized template.
  • L3 hides cost. One ApplicationLoadBalancedFargateService creates a load balancer, a cluster, a service, roles, log groups and security groups. Convenience is not free.
  • Library L3 patterns are generic, not secure by your standard. The Fargate pattern in this lesson opens its listener to the internet unless you pass OpenListener = false.
  • Your own L3 is a product. It needs versioning, tests, a changelog and an owner, or it becomes the next legacy template.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
ARM resource typesL1 Cfn* constructsGenerated from the resource specification; property names mirror CloudFormation
Bicep modules and Azure Verified ModulesL2 and L3 constructs, and your own construct librariesConstructs are C# classes with methods (GrantRead)
Azure role assignment resourcesGrants (bucket.GrantRead(role))One method call creates an IAM policy statement on the right principal
Azure Policy for deploymentsAspects, cdk-nag, testsChecks run at synthesis, before anything is deployed
Template specs shared in a registryNuGet package of constructsVersioned with SemVer, consumed with dotnet add package

Architecture

Security-boundary view. Controls live at three places: in the L3 (defaults the consumer cannot forget), in aspects and tests (checks that fail the build), and in the account (SCPs and Config rules that catch whatever slips through). Each layer assumes the one above can fail.

Step-by-step implementation

Read an L1 and an L2 side by side

Open the code under "Infrastructure as Code" and compare CfnBucket with Bucket. Count the lines.

Add a grant

Create a role and call GrantRead. Synthesize and read the IAM policy it generated, including the KMS permission.

Use an escape hatch

Take the L2 bucket's L1 child and set a property the L2 does not expose.

Write EvidenceBucket

Copy the construct from "Complete code" into your project from the previous lesson, and use it in a stack.

Add the aspect

Register RequireEncryptedBuckets, add a raw CfnBucket without encryption, and watch the CDK refuse to continue.

AWS Console instructions

Nothing is deployed in this lesson, so there is no console work. If you want to see the generated templates in the console, deploy the first-stack project from the previous lesson and open CloudFormation → Stacks → your stack → Template.

AWS CLI

All commands are local:

cdk synth -c owner=<your-name>            # writes cdk.out/, runs aspects, prints the template
cdk ls                                    # lists stacks
cdk synth 2>&1 | grep -i "error"          # aspect errors show as errors in the output

With a real stack in an account, cdk diff is how you review the effect of replacing an L2 with your L3.

Infrastructure as Code

L1, L2 and the escape hatch

using Amazon.CDK;
using Amazon.CDK.AWS.KMS;
using Amazon.CDK.AWS.S3;
using Constructs;

public sealed class ConstructLevelsStack : Stack
{
    public ConstructLevelsStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
    {
        var key = new Key(this, "Key", new KeyProps { EnableKeyRotation = true, RemovalPolicy = RemovalPolicy.DESTROY });

        // L1: one-to-one with AWS::S3::Bucket. You write the CloudFormation property tree yourself, nothing is defaulted.
        _ = new CfnBucket(this, "RawBucket", new CfnBucketProps
        {
            BucketEncryption = new CfnBucket.BucketEncryptionProperty
            {
                // L1 properties that accept "a list or a token" are typed object, so use an explicit object[].
                ServerSideEncryptionConfiguration = new object[]
                {
                    new CfnBucket.ServerSideEncryptionRuleProperty
                    {
                        BucketKeyEnabled = true,
                        ServerSideEncryptionByDefault = new CfnBucket.ServerSideEncryptionByDefaultProperty
                        {
                            SseAlgorithm = "aws:kms",
                            KmsMasterKeyId = key.KeyArn,
                        },
                    },
                },
            },
            PublicAccessBlockConfiguration = new CfnBucket.PublicAccessBlockConfigurationProperty
            {
                BlockPublicAcls = true,
                BlockPublicPolicy = true,
                IgnorePublicAcls = true,
                RestrictPublicBuckets = true,
            },
            VersioningConfiguration = new CfnBucket.VersioningConfigurationProperty { Status = "Enabled" },
        });

        // L2: the same intent in a few lines, with the TLS-only bucket policy added for you.
        var bucket = new Bucket(this, "Bucket", new BucketProps
        {
            Encryption = BucketEncryption.KMS,
            EncryptionKey = key,
            BlockPublicAccess = BlockPublicAccess.BLOCK_ALL,
            EnforceSSL = true,
            Versioned = true,
            RemovalPolicy = RemovalPolicy.DESTROY,
        });

        // Escape hatch: reach the L1 under an L2 for a property the L2 does not expose.
        var cfn = (CfnBucket)bucket.Node.DefaultChild!;
        cfn.AddPropertyOverride("ObjectLockEnabled", true);
        cfn.CfnOptions.UpdateReplacePolicy = CfnDeletionPolicy.RETAIN;
    }
}

This file was compiled and synthesized with Amazon.CDK.Lib 2.277.0; the override appears in the template as "ObjectLockEnabled": true.

L3 from the CDK library. One object, many resources. The OpenListener = false line matters: by default the pattern admits the whole internet to the load balancer.

using Amazon.CDK;
using Amazon.CDK.AWS.ECS;
using Amazon.CDK.AWS.ECS.Patterns;
using Constructs;

public sealed class LibraryPatternStack : Stack
{
    public LibraryPatternStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
    {
        _ = new ApplicationLoadBalancedFargateService(this, "Api", new ApplicationLoadBalancedFargateServiceProps
        {
            TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions
            {
                Image = ContainerImage.FromRegistry("public.ecr.aws/docker/library/nginx:stable"),
                ContainerPort = 80,
            },
            DesiredCount = 1,
            PublicLoadBalancer = true,
            OpenListener = false, // the pattern opens the listener to the world unless you say otherwise
        });
    }
}

L3 of your own: the lab's NatFreeVpc. The Module 10 project builds a two-AZ VPC with no NAT gateway, flow logs, a locked-down default security group and four interface endpoints, behind one constructor. The call site in the lab's FoundationStack is 6 lines:

Network = new NatFreeVpc(this, "Network", new NatFreeVpcProps
{
    NamePrefix = s.NamePrefix,
    Cidr = "10.60.0.0/16",
    LogKey = DataKey,
    FlowLogRetentionDays = p.LogRetentionDays,
});

The class (labs/m10-environment-two-tools/infra/cdk/Harbourline.Environment.Cdk/Patterns/NatFreeVpc.cs) is the model to copy: a sealed record for props, required members, a constructor that builds the resources, and public properties (Vpc, FlowLogGroup, EndpointSecurityGroup) for consumers.

Grants: IAM from intent

An L2 construct knows what each operation needs. bucket.GrantRead(role) adds an identity policy to the role with the S3 read actions on this bucket and its objects, and, because the bucket uses a customer managed key, the KMS decrypt permission as well. You write one line; the CDK writes the policy:

var reader = new Role(this, "Reader", new RoleProps { AssumedBy = new ServicePrincipal("ecs-tasks.amazonaws.com") });
evidence.GrantReader(reader);   // S3 read on the bucket and kms:Decrypt on the key, nothing more

Why this matters for security review: a reviewer reads GrantReader, not a 40-line policy. Why it needs care: the grant is only as narrow as the method. GrantReadWrite includes delete on some constructs. Check the generated statement in cdk diff, whose IAM table prints every statement.

Aspects: rules over the whole tree

An Aspect is an object that visits every construct during synthesis. Use it for organisation-wide rules: required tags, banned resource types, minimum settings. This one refuses any raw bucket that has no default encryption:

using Amazon.CDK;
using Amazon.CDK.AWS.S3;
using Amazon.JSII.Runtime.Deputy;
using Constructs;

public sealed class RequireEncryptedBuckets : DeputyBase, IAspect
{
    public void Visit(IConstruct node)
    {
        if (node is CfnBucket bucket && bucket.BucketEncryption is null)
        {
            Annotations.Of(node).AddError("S3 bucket has no default encryption. Use the EvidenceBucket construct or set BucketEncryption.");
        }
    }
}

Register it once: Aspects.Of(app).Add(new RequireEncryptedBuckets());. In C#, a class that implements a CDK interface must derive from DeputyBase (the jsii bridge base class). An error annotation is written into the cloud assembly and makes the CDK CLI stop (cdk synth and cdk deploy both fail), and Template.FromStack in a unit test throws. cdk-nag, used in Testing CDK, is a large collection of aspect-like rules.

Complete code

The reusable construct. Save as Constructs/EvidenceBucket.cs in the project from the previous lesson.

Constructs/EvidenceBucket.cs
using Amazon.CDK;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.KMS;
using Amazon.CDK.AWS.S3;
using Constructs;

namespace Harbourline.Evidence.Cdk.Constructs;

/// <summary>Options for <see cref="EvidenceBucket"/>.</summary>
public sealed record EvidenceBucketProps
{
    /// <summary>Environment name, used in the key alias. Production keeps its data on delete.</summary>
    public required string EnvironmentName { get; init; }

    /// <summary>Days to keep old object versions.</summary>
    public int NoncurrentVersionDays { get; init; } = 90;

    /// <summary>Use an existing key instead of creating one (for example a shared platform key).</summary>
    public IKey? EncryptionKey { get; init; }
}

/// <summary>
/// A Harbourline "L3" building block: a private, versioned, KMS-encrypted, TLS-only bucket with
/// server access logs. Application teams use this instead of hand-writing buckets, so the controls
/// are the same everywhere and reviewed once.
/// </summary>
public sealed class EvidenceBucket : Construct
{
    public EvidenceBucket(Construct scope, string id, EvidenceBucketProps props) : base(scope, id)
    {
        var isProd = props.EnvironmentName == "prod";
        var removal = isProd ? RemovalPolicy.RETAIN : RemovalPolicy.DESTROY;

        Key = props.EncryptionKey ?? new Key(this, "Key", new KeyProps
        {
            Alias = $"alias/hl-{props.EnvironmentName}-{id.ToLowerInvariant()}",
            Description = $"Harbourline {props.EnvironmentName}: encrypts {id}",
            EnableKeyRotation = true,
            PendingWindow = Duration.Days(7),
            RemovalPolicy = removal,
        });

        var logs = new Bucket(this, "Logs", new BucketProps
        {
            Encryption = BucketEncryption.S3_MANAGED,
            BlockPublicAccess = BlockPublicAccess.BLOCK_ALL,
            EnforceSSL = true,
            ObjectOwnership = ObjectOwnership.BUCKET_OWNER_ENFORCED,
            LifecycleRules = [new LifecycleRule { Id = "ExpireAccessLogs", Expiration = Duration.Days(90) }],
            RemovalPolicy = removal,
            AutoDeleteObjects = !isProd,
        });

        Bucket = new Bucket(this, "Bucket", new BucketProps
        {
            Encryption = BucketEncryption.KMS,
            EncryptionKey = Key,
            BucketKeyEnabled = true,
            BlockPublicAccess = BlockPublicAccess.BLOCK_ALL,
            EnforceSSL = true,
            Versioned = true,
            ObjectOwnership = ObjectOwnership.BUCKET_OWNER_ENFORCED,
            ServerAccessLogsBucket = logs,
            ServerAccessLogsPrefix = "evidence/",
            LifecycleRules = [new LifecycleRule { Id = "ExpireOldVersions", NoncurrentVersionExpiration = Duration.Days(props.NoncurrentVersionDays) }],
            RemovalPolicy = removal,
            AutoDeleteObjects = !isProd,
        });
    }

    public IKey Key { get; }
    public Bucket Bucket { get; }

    /// <summary>Lets a role put evidence in the bucket. Writers can never read or delete it.</summary>
    public Grant GrantWriter(IGrantable grantee) => Bucket.GrantPut(grantee);

    /// <summary>Lets a role read evidence. The grant includes the KMS permission the role needs.</summary>
    public Grant GrantReader(IGrantable grantee) => Bucket.GrantRead(grantee);
}

Using it in a stack:

var evidence = new EvidenceBucket(this, "Exports", new EvidenceBucketProps { EnvironmentName = "dev" });
evidence.GrantReader(auditorRole);
evidence.GrantWriter(exportJobRole);

To share it, put the class in its own class library project and publish a NuGet package (no jsii is needed when all consumers are C#; jsii is the tool for libraries that must also serve TypeScript or Python teams ⚠ VERIFY current guidance):

Harbourline.Constructs.csproj (excerpt)
<PropertyGroup>
  <PackageId>Harbourline.Constructs</PackageId>
  <Version>1.0.0</Version>
  <TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
  <PackageReference Include="Amazon.CDK.Lib" Version="2.277.0" />
</ItemGroup>

Code explained line by line

  1. sealed record EvidenceBucketProps. An immutable options object. required forces the caller to set EnvironmentName. A default on NoncurrentVersionDays means new options can be added later without breaking existing callers.
  2. : Construct and base(scope, id). An L3 is a plain Construct that creates children with this as the scope. It is not a resource itself. The children get paths such as Exports/Bucket/Resource.
  3. props.EncryptionKey ?? new Key(...). The consumer may bring a key (for example a platform key shared by an account) or let the construct create one. This is the usual L3 compromise: secure default, one override.
  4. id.ToLowerInvariant() in the alias. Derives a unique alias from the construct id so two EvidenceBucket instances in one account do not collide. (Aliases must be unique per account and Region.)
  5. removal. One decision (dev and test throw-away, prod retained) applied consistently to the key and both buckets.
  6. public IKey Key and public Bucket Bucket. Expose the children so consumers and tests can reach them, but keep the log bucket private: it is an implementation detail.
  7. GrantWriter and GrantReader. Domain-named wrappers over GrantPut and GrantRead. The names state intent ("writers can never read or delete"), which is what reviewers read.
  8. Aspect Visit. Called for every node. The is CfnBucket bucket pattern test narrows the type. Annotations.Of(node).AddError records an error against that exact construct path, so the message tells the author where to look.
  9. AddPropertyOverride("ObjectLockEnabled", true). Writes a raw property into the L1's CloudFormation properties. Use it sparingly: it bypasses the L2's validation, and an override can be wrong for a given Region or type.

Writing a construct library that lasts

  • Small, named by intent (EvidenceBucket, not BucketWithStuff).
  • Props records with required and defaults. Adding an optional property is a minor version; removing or changing a default is a major version.
  • Do not change logical IDs between versions. Renaming a child id inside the construct is a replacement for every consumer. Treat child ids as part of the public API, or use OverrideLogicalId to freeze them.
  • Test it. A unit test per control (Testing CDK) and a coarse snapshot catch regressions before consumers do.
  • Document the escape hatch. Say how to reach Bucket.Node.DefaultChild for exceptions, and who approves them.
  • Version with SemVer and publish release notes with the cdk diff impact of each release.

Security considerations

⚠ Learning shortcut — not for production

The construct sets AutoDeleteObjects for non-prod so the lab can destroy cleanly. That adds a Lambda function and an IAM role that can delete all objects in the bucket. A production-grade version would use S3 Object Lock, drop the auto-delete helper, replicate to a second Region and require two-person approval to change the key policy.

  • A construct is a security boundary only as strong as its tests. Someone can add a raw CfnBucket next to it. The aspect and cdk-nag catch that.
  • Grants widen over time. Prefer the narrowest method (GrantPut) and review the generated IAM table in cdk diff.
  • Library L3 patterns often favour convenience. Read the synthesized security groups and listeners (OpenListener above is a real example).
  • Escape hatches bypass safety. Require a comment and a reviewer for every AddPropertyOverride.
  • Supply chain. An internal construct package is code that runs at build time and writes IAM. Treat its repository like production code: protected branches, signed or pinned versions, dependency scanning.

Banking use case

Harbourline's platform team owns Harbourline.Constructs with three L3s: EvidenceBucket, PrivateApiService (Fargate behind a private ALB with WAF) and NatFreeVpc. A payments team needs a bucket for settlement files: new EvidenceBucket(this, "Settlements", ...) plus two grants. The pull request diff is five lines, the cdk diff shows the IAM statements, and the security reviewer only has to check the grants, because the controls are in the construct. When the bank adopts S3 Object Lock, one release of the package changes the default and every team sees it in their next cdk diff.

Common mistakes

  • Using L1 for everyday resources and forgetting a control. Prefer L2; keep L1 for new features and escape hatches.
  • Assuming an L3 is secure because it is "official". Check the synthesized template (OpenListener is the classic).
  • Breaking consumers with an innocent refactor, such as renaming a child id inside the construct.
  • Exposing too much (public props for every child) so consumers depend on internals.
  • Putting business logic in constructs (network calls, reading files at synthesis time, random values). Synthesis must be deterministic.
  • Using an object[] shortcut wrongly. L1 properties typed object accept either a list or a CDK token; a C# collection expression cannot be inferred for object, so write new object[] { ... } (the compiler error is CS9174).
  • Forgetting DeputyBase when implementing IAspect (the jsii bridge cannot call your class).

Troubleshooting

SymptomLikely causeFix
CS9174 Cannot initialize type 'object' with a collection expressionAn L1 property is typed objectUse new object[] { ... }
Aspect never runsNot registered, or registered after Synth()Aspects.Of(app).Add(...) before app.Synth()
Error "There is already a Construct with name 'Key'"Two children in the same scope with the same idUse unique ids per scope
cdk diff shows a replacement after a refactorA child id or path changedRestore the id, or freeze it with OverrideLogicalId
Cannot read properties of undefined from jsiiPassing null where a required value is expectedCheck required props; pass real values
Grant adds no KMS permissionThe key is imported with Key.FromKeyArn and the grant is cross-stack, or the principal is in another accountRead the generated IAM; add the key policy statement explicitly where needed
Raw CfnBucket errors "no default encryption"The aspect worksSwitch to EvidenceBucket or add encryption
NuGet restore fails with NU1605Explicit older Constructs referenceReference only Amazon.CDK.Lib

Cost and cleanup

Cost: free. This lesson only synthesizes templates on your machine. Nothing is deployed, so there is nothing to delete. If you deployed the previous lesson's stack and are still running it, destroy it with cdk destroy.

# nothing to tear down; remove generated output if you like
rm -rf cdk.out

Exercises

  • 🟢 Guided: add the EvidenceBucket to the project, synthesize, and confirm the template has TLS-deny statements and a KMS key. Add GrantReader for a role and read the generated policy in cdk.out.
  • 🟡 Challenge: add a RetentionMode option to EvidenceBucketProps that, when set to "object-lock", turns on Object Lock using the escape hatch. Decide what must also be true for Object Lock (versioning is already on) and document the limitation in the XML comment.
  • 🔴 Live problem: a team wants to use EvidenceBucket but needs a bucket without versioning for a high-churn temporary export. A deadline is tomorrow and the platform team is away. Propose the options (new construct, an explicit opt-out prop, a documented escape hatch), pick one, and write the risk statement a reviewer would sign.

Assignment

Create a class library Harbourline.Constructs in your portfolio repository containing EvidenceBucket and RequireEncryptedBuckets, a README.md describing the controls, versioning rules and the escape-hatch policy, and the NuGet metadata. Do not publish it to any public feed.

Solutions

Knowledge check

Interview questions

  • "What are L1, L2 and L3 constructs?" L1 are generated CloudFormation wrappers with no defaults, L2 are curated classes with defaults and helpers like grants, L3 are patterns combining several resources.
  • "How would you give 60 teams a safe bucket?" Publish a versioned EvidenceBucket L3 in an internal NuGet package with tests, add an aspect or cdk-nag to block raw buckets, and document the exemption route.
  • "What is an Aspect for?" To visit every construct during synthesis and enforce or modify something organisation-wide, such as adding tags or failing on a banned configuration.
  • "CDK constructs or Terraform modules for sharing patterns?" Constructs are typed, can generate IAM through grants and are tested with xUnit. Modules are plain HCL, readable by non-developers, and need no extra runtime. Choose by team skills (decision lesson).

Certification practice

Completion checklist

  • I can describe L1, L2 and L3 with an example of each
  • I used a grant and read the policy it generated
  • I used an escape hatch and saw it in the synthesized template
  • I wrote and used EvidenceBucket, and the aspect rejected a raw unencrypted bucket
  • I know why child ids are part of a library's public API

Key takeaways

  • L1 mirrors CloudFormation, L2 adds defaults and grants, L3 captures patterns.
  • Read the synthesized output, whatever level you use: convenience can hide settings.
  • Grants turn intent into IAM; review the generated statements.
  • Aspects enforce rules across the tree at synthesis time.
  • A construct library is a product: tests, SemVer, stable ids.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page