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.
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
- AWS CDK in C#: your first stack: the toolchain, the construct tree and logical IDs.
- AWS CloudFormation fundamentals: the property names that L1 constructs mirror.
- Tools: .NET 10 SDK, Node.js 22 or 24 LTS. No AWS account is needed: everything here is synthesized locally, and nothing is deployed.
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:
| Level | Name | What it is | Example | You choose |
|---|---|---|---|---|
| L1 | CFN resources | A 1:1 wrapper of a CloudFormation resource, generated from the CloudFormation specification | CfnBucket, CfnKey | Every property, exactly as in CloudFormation |
| L2 | Curated constructs | A hand-written class with a friendly API, defaults and helper methods | Bucket, Key, Role | The intent; defaults fill the rest |
| L3 | Patterns | A construct that creates several resources working together | ApplicationLoadBalancedFargateService, your own EvidenceBucket | A 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
ApplicationLoadBalancedFargateServicecreates 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 equivalent | What's different |
|---|---|---|
| ARM resource types | L1 Cfn* constructs | Generated from the resource specification; property names mirror CloudFormation |
| Bicep modules and Azure Verified Modules | L2 and L3 constructs, and your own construct libraries | Constructs are C# classes with methods (GrantRead) |
| Azure role assignment resources | Grants (bucket.GrantRead(role)) | One method call creates an IAM policy statement on the right principal |
| Azure Policy for deployments | Aspects, cdk-nag, tests | Checks run at synthesis, before anything is deployed |
| Template specs shared in a registry | NuGet package of constructs | Versioned 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 outputWith 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 moreWhy 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.
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):
<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
sealed record EvidenceBucketProps. An immutable options object.requiredforces the caller to setEnvironmentName. A default onNoncurrentVersionDaysmeans new options can be added later without breaking existing callers.: Constructandbase(scope, id). An L3 is a plainConstructthat creates children withthisas the scope. It is not a resource itself. The children get paths such asExports/Bucket/Resource.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.id.ToLowerInvariant()in the alias. Derives a unique alias from the construct id so twoEvidenceBucketinstances in one account do not collide. (Aliases must be unique per account and Region.)removal. One decision (dev and test throw-away, prod retained) applied consistently to the key and both buckets.public IKey Keyandpublic Bucket Bucket. Expose the children so consumers and tests can reach them, but keep the log bucket private: it is an implementation detail.GrantWriterandGrantReader. Domain-named wrappers overGrantPutandGrantRead. The names state intent ("writers can never read or delete"), which is what reviewers read.- Aspect
Visit. Called for every node. Theis CfnBucket bucketpattern test narrows the type.Annotations.Of(node).AddErrorrecords an error against that exact construct path, so the message tells the author where to look. 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, notBucketWithStuff). - Props records with
requiredand 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
OverrideLogicalIdto 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.DefaultChildfor exceptions, and who approves them. - Version with SemVer and publish release notes with the
cdk diffimpact 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
CfnBucketnext to it. The aspect and cdk-nag catch that. - Grants widen over time. Prefer the narrowest method (
GrantPut) and review the generated IAM table incdk diff. - Library L3 patterns often favour convenience. Read the synthesized security groups and listeners (
OpenListenerabove 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 (
OpenListeneris 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 typedobjectaccept either a list or a CDK token; a C# collection expression cannot be inferred forobject, so writenew object[] { ... }(the compiler error is CS9174). - Forgetting
DeputyBasewhen implementingIAspect(the jsii bridge cannot call your class).
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
CS9174 Cannot initialize type 'object' with a collection expression | An L1 property is typed object | Use new object[] { ... } |
| Aspect never runs | Not 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 id | Use unique ids per scope |
cdk diff shows a replacement after a refactor | A child id or path changed | Restore the id, or freeze it with OverrideLogicalId |
Cannot read properties of undefined from jsii | Passing null where a required value is expected | Check required props; pass real values |
| Grant adds no KMS permission | The key is imported with Key.FromKeyArn and the grant is cross-stack, or the principal is in another account | Read the generated IAM; add the key policy statement explicitly where needed |
Raw CfnBucket errors "no default encryption" | The aspect works | Switch to EvidenceBucket or add encryption |
| NuGet restore fails with NU1605 | Explicit older Constructs reference | Reference 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.outExercises
- 🟢 Guided: add the
EvidenceBucketto the project, synthesize, and confirm the template has TLS-deny statements and a KMS key. AddGrantReaderfor a role and read the generated policy incdk.out. - 🟡 Challenge: add a
RetentionModeoption toEvidenceBucketPropsthat, 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
EvidenceBucketbut 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
The synthesized template for EvidenceBucket contains two buckets, two bucket policies (one TLS-deny statement each, plus the log-delivery statement), the key and alias, and the auto-delete helper resources in dev. GrantReader(role) adds an AWS::IAM::Policy for the role with S3 read actions on the bucket and objects and kms:Decrypt (plus related KMS read actions) on the key. Seeing the generated policy is the point: you can explain exactly what the one line grants.
Add public bool ObjectLock { get; init; } (an enum or string works too). After creating the bucket: if (props.ObjectLock) { ((CfnBucket)Bucket.Node.DefaultChild!).AddPropertyOverride("ObjectLockEnabled", true); }. Object Lock requires versioning, which the construct already enables. Document that Object Lock is normally chosen when the bucket is created and enabling it later has conditions (⚠ VERIFY the current rule), that a retention configuration is a separate decision, and that the default retention mode must be chosen by compliance. Add a unit test that the override appears.
Option A, a new construct for ephemeral exports, avoids weakening the main one but adds another thing to maintain. Option B, an explicit Versioned prop defaulting to true, is simple but makes the insecure path one word away and visible in every diff. Option C, telling the team to use the escape hatch, hides the exception. A reasonable answer: B with a required justification string (VersioningExemptionReason) that the construct writes into a tag, plus a lifecycle rule that expires everything in seven days, and an alert on any non-versioned EvidenceBucket. The risk statement says: data in this bucket is temporary, reproducible, contains no customer data, and is deleted within seven days; approved by the data owner and the security reviewer.
Knowledge check
Answer: A generated one-to-one wrapper of a CloudFormation resource (Cfn*). It has no defaults and no helper methods; you set every property as in the CloudFormation reference.
Answer: It adds an IAM policy to the role allowing the S3 read actions on that bucket and its objects, and the KMS decrypt permission if the bucket uses a customer managed key. It generates the statements from intent so you do not hand-write them.
Answer: When an L2 does not expose a CloudFormation property you need. Reach the L1 via Node.DefaultChild and use AddPropertyOverride or CfnOptions. Use it sparingly, because it bypasses the L2's validation.
Answer: The CDK library runs in Node.js; jsii calls back into your C# object through a bridge that requires the class to derive from the jsii base class DeputyBase.
Answer: The ids form the path that produces the logical IDs. Changing one makes CloudFormation replace the resource in every stack that uses the library.
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
EvidenceBucketL3 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
A DevOps team wants every application team to deploy S3 buckets with encryption, TLS enforcement and logging by default, and to block deployments that create unencrypted buckets. Which CDK approach best achieves this?
A. A wiki page with example code.
B. A shared construct library with an EvidenceBucket L3 plus an aspect that raises an error for unencrypted CfnBucket resources.
C. Ask each team to copy the CloudFormation template.
D. Use only L1 constructs so every property is explicit.
Answer: B. A shared L3 puts the controls in one reviewed place, and an aspect fails synthesis for violations. A and C rely on discipline and drift. D increases the chance of forgetting a control.
An architect uses a CDK L2 construct but needs a CloudFormation property that the construct does not expose. What is the recommended approach?
A. Fork the CDK library.
B. Access the underlying L1 resource through Node.DefaultChild and set the property with AddPropertyOverride.
C. Switch the whole stack to hand-written YAML.
D. Wait for the property to be added.
Answer: B. The escape hatch is designed for this. A is heavy and hard to maintain. C discards the benefits of the CDK. D blocks delivery.
After a refactor, cdk diff shows that a production DynamoDB table will be removed and a new one created, although the code only renamed a construct id. What is the cause?
A. The CDK always replaces tables on deployment. B. The construct id is part of the logical ID, so a new id creates a new resource. C. The CloudFormation template exceeded the size limit. D. A feature flag was set to true.
Answer: B. A new id changes the logical ID. Revert the rename, or keep the old logical ID with OverrideLogicalId. The other options do not explain the symptom.
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.
Related lessons and next steps
- Previous: AWS CDK in C#: your first stack
- Next: CDK stacks, environments and configuration
- Then: Testing CDK
- Compare with: Terraform modules
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.
AWS CDK in C#: your first stack
Create a CDK app in C#, understand the construct tree, and use cdk synth, cdk diff, cdk deploy and cdk destroy to build the audit-evidence bucket from the CloudFormation lesson as typed, testable code.
CDK stacks, environments and configuration
Split an app into stacks by lifecycle, pass values between them without creating dependency cycles, drive dev, test and prod from one codebase with typed settings, and understand what cdk bootstrap creates and how to narrow it.