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.
Assumes: .NET 10 LTS · Amazon.CDK.Lib 2.277.0 · AWS CDK CLI v2 (npm aws-cdk) · Node.js 22 LTS · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Explain what the CDK is and why a C# app can still end up as a CloudFormation stack.
- Install the toolchain (Node.js, the CDK CLI, the .NET 10 SDK) and bootstrap an account once.
- Read the construct tree (App, Stack, construct, L1 resource) and predict the logical IDs it produces.
- Write a stack with typed props classes, run
cdk synth,cdk diffandcdk deploy, and read each output. - Explain feature flags in
cdk.jsonand fix the one that this lesson's bucket needs. - Destroy the stack and confirm nothing is left billing.
Prerequisites
- AWS CloudFormation fundamentals: you will recognise every property in the synthesized template.
- Why infrastructure as code
- Tools: .NET 10 SDK, Node.js 22 or 24 LTS (the CDK runs its construct library in Node), the CDK CLI (
npm install -g aws-cdk), AWS CLI v2 with thelearn-sandboxprofile.
Why this matters in banking
A CloudFormation template for a real platform runs to thousands of lines. Nobody can review that, and copy-pasted YAML drifts between teams. C# gives you what you already use in the bank: types, loops, functions, packages and unit tests. A change such as "every bucket must have TLS enforced and a key" becomes one class used everywhere, with a compile error when someone forgets a required property.
The cost is a new failure mode: a code change can silently produce a big template change. That is why this lesson spends as much time on cdk diff and the construct tree as on writing the code.
The idea in plain language
The AWS Cloud Development Kit (CDK) is a library of classes. Each class stands for an AWS resource, or for a ready-made group of resources. You create objects in C#; when your program ends, the CDK writes a cloud assembly: one CloudFormation template per stack, plus any files (Lambda code, Docker images) the stacks need. The CDK CLI then hands the templates to CloudFormation.
Your C# runs only on your machine or in the build, at synthesis time. It never runs inside AWS during deployment.
Analogy: a CDK app is a drafting program. You tell it "this wall, this door, this window" in C# and it prints the architect's drawings (CloudFormation). The builders (CloudFormation) only ever see the drawings. Reviewers can read both: the program, and the drawing it printed.
Three words you will use constantly:
| Term | Meaning |
|---|---|
| App | The root object. One per program (new App()) |
| Stack | A unit of deployment. One stack becomes one CloudFormation stack |
| Construct | Any building block. L1 constructs map one-to-one to CloudFormation resources; L2 and L3 wrap them (next lesson) |
What problem the CDK solves
| Problem with raw templates | CDK answer |
|---|---|
| No types: a typo in a property name is found at deploy time | The C# compiler finds it |
| Copy-paste reuse | Classes and NuGet packages |
| IAM policies written by hand | bucket.GrantRead(role) writes the policy statement |
| Hard to test | xUnit tests over the synthesized template (Testing CDK) |
| Defaults you must remember | L2 constructs ship sensible, secure defaults |
Honest limits
- You need Node.js even though you write C#, because the CDK library is TypeScript that .NET calls through a bridge called jsii. Start-up is slower than a plain .NET app (seconds).
- The CDK produces CloudFormation, so CloudFormation limits and error messages still apply.
- Abstraction hides detail. One
new Bucket(...)can create several resources (the auto-delete helper in this lesson creates a Lambda function and an IAM role). Always read the synthesized template. - A CDK upgrade can change generated templates. Pin versions and read
cdk diffafter upgrades.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Bicep | AWS CDK | Bicep is a DSL; the CDK is real C# (or TypeScript, Python, Java, Go) |
| Pulumi (C#) | AWS CDK (C#) | Pulumi talks to cloud APIs directly and keeps state; the CDK compiles to CloudFormation and AWS keeps the state |
ARM template output (az bicep build) | cdk synth | Both produce the deployable template |
az deployment what-if | cdk diff | cdk diff also highlights IAM and security group changes |
| NuGet package of Azure resources | NuGet packages Amazon.CDK.Lib and your own construct library | One big package holds all stable AWS constructs |
az bicep modules | Constructs | A construct is a class you instantiate, not a file you reference |
Architecture
Security-boundary view. Three identities are involved. Your CLI credentials (the SSO session) call CloudFormation. CloudFormation then uses a CloudFormation execution role created by bootstrapping to create resources. File assets go through a file-publishing role. By default bootstrapping gives the execution role broad permissions, which is acceptable in a sandbox but should be narrowed in production (see lesson 6).
The construct tree
Every object lives in a tree. The path of a construct becomes its CloudFormation logical ID (with a hash), so IDs are not cosmetic.
The L1 child is always called Resource. The synthesized logical ID for AuditBucket/Resource is AuditBucketB01E0AE8: the path without Resource, plus an eight-character hash. If you rename the id AuditBucket to Evidence, the logical ID changes, and CloudFormation sees a delete plus a create. That is the CDK equivalent of renaming a resource in a template.
Step-by-step implementation
Install the tools
node --version # expect v22.x or v24.x
npm install -g aws-cdk
cdk --version
dotnet --version # expect 10.0.xThe CDK CLI (aws-cdk on npm) and the construct library (Amazon.CDK.Lib on NuGet) have separate version numbers. The CLI must be new enough to read what the library produces; keeping the CLI current is the normal fix when cdk complains about a "cloud assembly schema version".
Bootstrap the account once
Assets (here, the helper Lambda that empties buckets on destroy) need somewhere to be uploaded. cdk bootstrap creates that place: a stack named CDKToolkit with an S3 bucket, an ECR repository and IAM roles.
ACCOUNT=$(aws sts get-caller-identity --profile learn-sandbox --query Account --output text)
cdk bootstrap aws://$ACCOUNT/us-east-1 --profile learn-sandboxYou do this once per account and Region. Lesson 6 explains what it creates and how to lock it down.
Create the project
Make a folder and add the four files from "Complete code". You can instead run cdk init app --language csharp in an empty folder and replace its generated files; the generated layout puts the project under src/ ⚠ VERIFY the exact generated layout for your CLI version.
Synthesize
cdk synth -c owner=<your-name>Open cdk.out/hl-m10-cdk-dev-evidence.template.json and compare it with the YAML from the CloudFormation lesson.
Diff, then deploy
cdk diff -c owner=<your-name> --profile learn-sandbox
cdk deploy -c owner=<your-name> --profile learn-sandboxChange something and diff again
Change NoncurrentVersionDays to 120 and run cdk diff. You should see a single modification in the audit bucket's lifecycle rules.
Destroy
cdk destroy -c owner=<your-name> --profile learn-sandboxAWS Console instructions
Console → CloudFormation → Stacks. After cdk bootstrap you see CDKToolkit; after cdk deploy you see hl-m10-cdk-dev-evidence. The Template tab shows the synthesized template, and the Resources tab shows each logical ID next to its physical ID. Resources → AuditBucketB01E0AE8 links to the S3 console. Notice the Tags tab: the four lab tags were applied by the CDK to every taggable resource.
AWS CLI
The cdk command is the main tool. Useful commands:
cdk ls # stack names in the app
cdk synth # write cdk.out/ and print the template of one stack
cdk diff # compare the app with the deployed stack
cdk deploy --require-approval broadening # ask before IAM or security-group widening (the default)
cdk deploy --outputs-file outputs.json # save CfnOutput values
cdk deploy --method prepare-change-set # create the change set, do not execute it ⚠ VERIFY option for your CLI version
cdk destroy # delete the stack
cdk doctor # print version and environment information
cdk context # show cached context (lookups)AWS CLI commands you still use around it:
aws cloudformation describe-stacks --stack-name hl-m10-cdk-dev-evidence --profile learn-sandbox \
--query "Stacks[0].[StackStatus,Outputs]"
aws cloudformation describe-stack-events --stack-name hl-m10-cdk-dev-evidence --profile learn-sandbox \
--query "StackEvents[?ResourceStatus=='CREATE_FAILED'].[LogicalResourceId,ResourceStatusReason]" --output tableWhat cdk diff prints
cdk diff compares the template it just synthesized with the deployed one and prints a summary with [+] for additions, [-] for removals and [~] for modifications. An abbreviated example for the lifecycle change:
Stack hl-m10-cdk-dev-evidence
Resources
[~] AWS::S3::Bucket AuditBucket AuditBucketB01E0AE8
└─ [~] LifecycleConfiguration
└─ [~] .Rules:
└─ @@ -1,5 +1,5 @@
[ ] "NoncurrentVersionExpiration": {
[-] "NoncurrentDays": 90
[+] "NoncurrentDays": 120
[ ] },Treat this exactly like a pull-request diff. Look for [-] on stateful resources, for IAM statements (the CLI prints a separate "IAM Statement Changes" table) and for security group changes. cdk diff returns a non-zero exit code with --fail when there are differences, which is useful in a pipeline gate ⚠ VERIFY the flag name in cdk diff --help.
Infrastructure as Code
The whole lesson is the CDK. The Terraform tab maps the workflow.
The core of the stack, the audit bucket, in 15 lines (the full file is under "Complete code"):
AuditBucket = new Bucket(this, "AuditBucket", new BucketProps
{
Encryption = BucketEncryption.KMS,
EncryptionKey = DataKey,
BucketKeyEnabled = true,
BlockPublicAccess = BlockPublicAccess.BLOCK_ALL,
EnforceSSL = true,
Versioned = true,
ObjectOwnership = ObjectOwnership.BUCKET_OWNER_ENFORCED,
ServerAccessLogsBucket = logs,
ServerAccessLogsPrefix = "audit-bucket/",
RemovalPolicy = removal,
});An excerpt of what cdk synth produced for it (real output from this code, trimmed):
"AuditBucketB01E0AE8": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketEncryption": { "ServerSideEncryptionConfiguration": [ {
"BucketKeyEnabled": true,
"ServerSideEncryptionByDefault": { "KMSMasterKeyID": { "Fn::GetAtt": ["DataKey17AFBB84", "Arn"] }, "SSEAlgorithm": "aws:kms" } } ] },
"LoggingConfiguration": { "DestinationBucketName": { "Ref": "AccessLogs8B620ECA" }, "LogFilePrefix": "audit-bucket/" },
"OwnershipControls": { "Rules": [ { "ObjectOwnership": "BucketOwnerEnforced" } ] },
"PublicAccessBlockConfiguration": { "BlockPublicAcls": true, "BlockPublicPolicy": true, "IgnorePublicAcls": true, "RestrictPublicBuckets": true },
"VersioningConfiguration": { "Status": "Enabled" }
},
"UpdateReplacePolicy": "Delete",
"DeletionPolicy": "Delete"
}For the dev stack the synthesized app has 10 resources: 2 buckets, 2 bucket policies (TLS-only statements plus log delivery), the key and its alias, two Custom::S3AutoDeleteObjects resources and the helper Lambda function and role.
Complete code
Folder layout:
iac-m10/cdk-first/
├── cdk.json
└── Harbourline.Evidence.Cdk/
├── Harbourline.Evidence.Cdk.csproj
├── Program.cs
└── EvidenceStack.cs{
"app": "dotnet run --project Harbourline.Evidence.Cdk/Harbourline.Evidence.Cdk.csproj",
"watch": {
"include": ["**"],
"exclude": ["README.md", "cdk*.json", "**/bin", "**/obj"]
},
"context": {
"environmentName": "dev",
"owner": "your-name",
"@aws-cdk/core:target-partitions": ["aws"],
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true
}
}<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>Harbourline.Evidence.Cdk</RootNamespace>
<!-- jsii-generated CDK types mark some members obsolete; keep the warnings visible but not fatal. -->
<WarningsNotAsErrors>CS0618</WarningsNotAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.CDK.Lib" Version="2.277.0" />
</ItemGroup>
</Project>using Amazon.CDK;
using Harbourline.Evidence.Cdk;
var app = new App();
// Settings come from cdk.json "context" or from -c key=value on the command line.
var environmentName = app.Node.TryGetContext("environmentName")?.ToString() ?? "dev";
var owner = app.Node.TryGetContext("owner")?.ToString();
if (string.IsNullOrWhiteSpace(owner) || owner == "your-name")
{
throw new InvalidOperationException("Set -c owner=<your-name> so the Owner tag says who to ask about these resources.");
}
_ = new EvidenceStack(app, $"hl-m10-cdk-{environmentName}-evidence", new EvidenceStackProps
{
EnvironmentName = environmentName,
// The CLI fills CDK_DEFAULT_ACCOUNT from your profile, so no account ID is ever written in code.
Env = new Amazon.CDK.Environment
{
Account = System.Environment.GetEnvironmentVariable("CDK_DEFAULT_ACCOUNT"),
Region = "us-east-1",
},
Description = "Harbourline m10: audit-evidence bucket with a customer managed key (CDK C# first stack)",
});
// Tags added to the app flow down to every taggable resource in every stack.
Tags.Of(app).Add("Project", "cea-lab");
Tags.Of(app).Add("Lab", "m10-cdk-first");
Tags.Of(app).Add("Environment", "learn");
Tags.Of(app).Add("Owner", owner);
app.Synth();using Amazon.CDK;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.KMS;
using Amazon.CDK.AWS.S3;
using Constructs;
namespace Harbourline.Evidence.Cdk;
/// <summary>Options for <see cref="EvidenceStack"/>. A props class is the C# way to give a stack typed inputs.</summary>
public sealed class EvidenceStackProps : StackProps
{
public required string EnvironmentName { get; init; }
public int NoncurrentVersionDays { get; init; } = 90;
}
/// <summary>
/// The same audit-evidence bucket as the CloudFormation lesson, written as C#:
/// a customer managed key, a private TLS-only versioned bucket encrypted with it, and an access-log bucket.
/// </summary>
public sealed class EvidenceStack : Stack
{
public EvidenceStack(Construct scope, string id, EvidenceStackProps props) : base(scope, id, props)
{
var prefix = $"hl-m10-cdk-{props.EnvironmentName}";
var isProd = props.EnvironmentName == "prod";
// dev and test are throw-away; prod keeps its data when the stack is deleted.
var removal = isProd ? RemovalPolicy.RETAIN : RemovalPolicy.DESTROY;
DataKey = new Key(this, "DataKey", new KeyProps
{
Alias = $"alias/{prefix}-audit",
Description = $"Harbourline {props.EnvironmentName}: encrypts the audit-evidence bucket",
EnableKeyRotation = true,
PendingWindow = Duration.Days(7),
RemovalPolicy = removal,
});
var logs = new Bucket(this, "AccessLogs", new BucketProps
{
Encryption = BucketEncryption.S3_MANAGED, // server access logs cannot be delivered to a KMS-encrypted bucket
BlockPublicAccess = BlockPublicAccess.BLOCK_ALL,
EnforceSSL = true,
ObjectOwnership = ObjectOwnership.BUCKET_OWNER_ENFORCED,
LifecycleRules = [new LifecycleRule { Id = "ExpireAccessLogs", Expiration = Duration.Days(90) }],
RemovalPolicy = removal,
AutoDeleteObjects = !isProd, // a helper Lambda empties the bucket on destroy (learning convenience)
});
AuditBucket = new Bucket(this, "AuditBucket", new BucketProps
{
Encryption = BucketEncryption.KMS,
EncryptionKey = DataKey,
BucketKeyEnabled = true,
BlockPublicAccess = BlockPublicAccess.BLOCK_ALL,
EnforceSSL = true,
Versioned = true,
ObjectOwnership = ObjectOwnership.BUCKET_OWNER_ENFORCED,
ServerAccessLogsBucket = logs,
ServerAccessLogsPrefix = "audit-bucket/",
LifecycleRules =
[
new LifecycleRule { Id = "ExpireOldVersions", NoncurrentVersionExpiration = Duration.Days(props.NoncurrentVersionDays) },
new LifecycleRule { Id = "AbortIncompleteUploads", AbortIncompleteMultipartUploadAfter = Duration.Days(7) },
],
RemovalPolicy = removal,
AutoDeleteObjects = !isProd,
});
if (isProd)
{
// In prod nobody may permanently delete an object version. (S3 Object Lock is the stronger control.)
AuditBucket.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps
{
Sid = "DenyPermanentDeletes",
Effect = Effect.DENY,
Principals = [new AnyPrincipal()],
Actions = ["s3:DeleteObjectVersion"],
Resources = [AuditBucket.ArnForObjects("*")],
}));
}
_ = new CfnOutput(this, "BucketName", new CfnOutputProps { Value = AuditBucket.BucketName, Description = "Audit-evidence bucket name" });
_ = new CfnOutput(this, "KeyArn", new CfnOutputProps { Value = DataKey.KeyArn, Description = "Customer managed key for the audit bucket" });
}
public Key DataKey { get; }
public Bucket AuditBucket { get; }
}This code was built with Amazon.CDK.Lib 2.277.0 on .NET 10 and synthesized with Node.js 22 to confirm the output shown above.
Code explained line by line
new App(). The root of the tree. With no arguments it writes the cloud assembly tocdk.out/(the CLI sets the output folder through an environment variable).app.Node.TryGetContext("owner"). Context is a bag of key/value settings fromcdk.json, from-c key=value, or from the CLI's lookups. The program refuses to synthesize with the placeholder owner, so a missing tag is caught on your laptop.new Amazon.CDK.Environment { ... }. The full name is needed because plainEnvironmentis ambiguous withSystem.Environmentin C#. When the account isnulland the CLI runs the app, CDK still deploys to the profile's account, but cross-account lookups and some features need a concrete account.CDK_DEFAULT_ACCOUNTis filled in by the CLI.Tags.Of(app).Add(...). A tag added at the app level is applied to every taggable resource below. TheAmazon.CDK.Tagsclass is available in a top-level program. Inside aStacksubclass you must writeAmazon.CDK.Tags.Of(this)becauseTagsresolves to the stack's ownTagsproperty (compile error CS0176).EvidenceStackProps : StackProps. TherequiredC# keyword makes the compiler refuse anEvidenceStackPropswithoutEnvironmentName. This is the main reason to prefer a CDK app over YAML for shared stacks.RemovalPolicy. The CDK's name forDeletionPolicyplusUpdateReplacePolicy.DESTROYbecomesDelete,RETAINbecomesRetain. Dev and test are disposable, prod is not.new Key(this, "DataKey", ...). The first argument is the scope (the parent in the tree), the second is the id (unique among siblings), the third is the props. Every construct constructor has this shape.AutoDeleteObjects = !isProd. A bucket with objects cannot be deleted. The CDK solves that with a helper Lambda function (and an IAM role) behind a custom resource that empties the bucket when the stack is deleted. It requiresRemovalPolicy.DESTROYand the bootstrap stack.BucketKeyEnabled = true. Reduces KMS requests, as in the CloudFormation lesson.ServerAccessLogsBucket = logs. The CDK adds the bucket policy that lets the S3 logging service write. This is where the feature flag matters, see below.LifecycleRules = [ ... ]. C# 12 collection expressions fill the array type that jsii expects.AuditBucket.AddToResourcePolicy(...). Adds a statement to the bucket policy.ArnForObjects("*")builds the object ARN pattern. This is imperative code generating a declarative statement; theif (isProd)exists only at synthesis time, and the dev template simply does not contain the statement.CfnOutput. Becomes anOutputsentry. Property names stay as properties so tests can readAuditBucketandDataKey.
Feature flags: why cdk.json matters
New behaviours that would change existing templates are hidden behind feature flags in the context section of cdk.json. cdk init writes the current recommended flags into new projects. If you write cdk.json by hand you get the old behaviour for flags you did not set.
This lesson hit one. Without "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true, the CDK tries to give the log bucket an ACL (LogDeliveryWrite), which conflicts with BucketOwnerEnforced (ACLs disabled). The synthesis fails with a message that says objectOwnership must be set to "ObjectWriter" when accessControl is "LogDeliveryWrite". The flag switches the CDK to the bucket-policy approach, which works with modern buckets.
Two rules follow. First, start from cdk init and keep its flags. Second, treat a flag change like a dependency upgrade: cdk diff before and after, because flags change generated templates (some flags cause replacement of resources). ⚠ VERIFY the current list of recommended flags with cdk flags or the CDK documentation when you create a project.
Security considerations
⚠ Learning shortcut — not for production
AutoDeleteObjects = true installs a helper Lambda and role that can delete every object in the bucket. That is convenient for dev and test and unacceptable for evidence data, which is why the code turns it off (and retains the bucket and key) in prod. Also, you deploy from your own SSO session with a bootstrap execution role that is broad by default. In production a pipeline role deploys, the execution policy is narrowed, and cdk deploy is never run from a laptop.
- The synthesized template is your security review artefact. Review it, or scan it (cdk-nag in Testing CDK). Do not trust a construct because it is "AWS-made": read the policies it generates.
- No secrets in code or context.
cdk.jsonis committed to Git. Put only non-secret settings there. cdk deployprompts when permissions broaden. Do not disable--require-approvalin pipelines without another gate such as a reviewedcdk diff.- Pin versions.
Amazon.CDK.Lib2.277.0 here. A floating version makes builds irreproducible, and a template diff in the middle of an unrelated change is a bad surprise. - Region and partition. Hard-coding
us-east-1in the app is fine for this lab. In a bank, residency (UK or EU Regions for UK GDPR) is decided in a documented configuration, not scattered in code. See UK GDPR and data residency.
Banking use case
Harbourline's platform team publishes an EvidenceBucket class in an internal NuGet package. Application teams call new EvidenceBucket(this, "Exports", ...) and cannot forget encryption, TLS, versioning or logging because the class sets them. The security team reviews the class once and a unit test proves each property (Testing CDK). Because every use goes through the same class, a later change (for example moving to an Object Lock default) is one pull request that cdk diff shows in every consuming stack.
Common mistakes
- Reusing a construct ID by accident. Two siblings with the same id throw
There is already a Construct with name '...'. - Renaming a construct id of a stateful resource. It changes the logical ID and causes a replacement. Run
cdk diffand look for[-]plus[+]pairs. - Writing C# conditions that depend on deploy-time values. Values such as
bucket.BucketNameare tokens until deployment; they are placeholders, not strings.if (bucket.BucketName.StartsWith("x"))does not do what you expect. Use CloudFormation conditions or make the decision from your own inputs. - Forgetting
cdk bootstrap. Error: "This stack uses assets, so the toolkit stack must be deployed". - Mixing CLI and library versions that cannot understand each other. Update the CLI (
npm install -g aws-cdk@latest). - Not committing
cdk.jsonor editing flags without a diff. - Using
Amazon.CDK.Tags.Of(this)inside a stack without theAmazon.CDK.prefix (error CS0176). - Adding an explicit
Constructspackage reference with an older version thanAmazon.CDK.Libneeds. NuGet reports a downgrade error (NU1605). Reference onlyAmazon.CDK.Lib; it bringsConstructswith it.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Unable to find ... node or the app hangs at start | Node.js missing or too old | Install Node.js 22 or 24 LTS and open a new terminal |
| Node warns that your Node version is end-of-life | Old Node (for example 18) | Upgrade to a supported LTS release |
objectOwnership must be set to "ObjectWriter"... | Missing serverAccessLogsUseBucketPolicy flag | Add the flag to cdk.json context (see above) |
This stack uses assets, so the toolkit stack must be deployed | Account not bootstrapped | cdk bootstrap aws://<account>/us-east-1 --profile learn-sandbox |
Need to perform AWS calls for account ... but no credentials found | SSO session expired or no --profile | aws sso login --profile learn-sandbox and pass --profile |
Set -c owner=<your-name> ... | The guard in Program.cs | Add -c owner=<your-name> |
| NU1605 package downgrade | Explicit Constructs reference older than the library's | Remove the explicit reference |
CS0176 on Amazon.CDK.Tags.Of(this) | Tags resolves to the stack's property | Amazon.CDK.Tags.Of(this) |
AWS::S3::Bucket ... already exists | A retained bucket from another run has the same name | Let the CDK generate names (as here) instead of fixed bucket names |
cdk diff shows more than you changed | Library or flag change | Read the diff before deploying; pin versions |
Cost and cleanup
Cost: credits. The CDK is free. The customer managed key costs about 1 US dollar per month, prorated hourly (⚠ VERIFY current KMS pricing), the helper Lambda and buckets cost fractions of a cent, and the bootstrap stack's bucket and roles cost almost nothing. A one-hour run costs far less than a cent apart from the prorated key.
cdk destroy -c owner=<your-name> --profile learn-sandbox
# confirm the lab resources are gone (the key shows PendingDeletion for 7 days; that is expected)
aws resourcegroupstaggingapi get-resources --profile learn-sandbox --region us-east-1 \
--tag-filters Key=Lab,Values=m10-cdk-first --query "ResourceTagMappingList[].ResourceARN"With RemovalPolicy.DESTROY the CDK deletes the key through the standard scheduled deletion (the PendingWindow of 7 days), not immediately. The bootstrap stack CDKToolkit is shared by later labs; keep it, it is almost free. To remove it entirely, delete its stack after emptying its bucket.
Exercises
- 🟢 Guided: build the project, run
cdk synth, findAuditBucketB01E0AE8in the template, deploy, read the outputs, changeNoncurrentVersionDaysto 120 and read the diff, then destroy. - 🟡 Challenge: add an
AccessLogRetentionDaysproperty toEvidenceStackProps(default 90) and use it for the log bucket's expiration. Runcdk diffto confirm that the default produces no change to the deployed stack. - 🔴 Live problem: a colleague renamed the construct id
AuditBuckettoEvidenceBucketin a pull request and wrote "refactor only, no functional change". The stack isprodwithRETAIN. Explain whatcdk diffwill show, what would happen on deploy, and how to rename safely.
Assignment
Create a cdk/evidence-first/ folder in your portfolio repository with the four files, a README.md listing the commands (bootstrap, synth, diff, deploy, destroy), and a screenshot-free "what I learned" paragraph covering feature flags and logical IDs.
Solutions
cdk synth writes cdk.out/hl-m10-cdk-dev-evidence.template.json. The audit bucket is AuditBucketB01E0AE8 (the hash may differ if you change ids). After the change to 120 days, cdk diff shows one [~] on that bucket's LifecycleConfiguration, changing NoncurrentDays from 90 to 120. Seeing that the diff contains only the thing you changed is the proof that the change is safe.
Add public int AccessLogRetentionDays { get; init; } = 90; to the props class and use Expiration = Duration.Days(props.AccessLogRetentionDays) in the AccessLogs rule. With the default of 90, the synthesized template is byte-for-byte the same for that rule, so cdk diff prints "There were no differences". Defaults that preserve current behaviour are how you add options without surprising consumers.
The logical ID of the bucket derives from the path, so it changes. cdk diff will show [-] for the old bucket and [+] for a new one. With RemovalPolicy.RETAIN, CloudFormation will not delete the old bucket (it is orphaned, still full of evidence) and will create an empty new one with a different generated name. The application would start writing to a bucket that has none of the history. The pull request is not a refactor. To rename safely: keep the old id, or use OverrideLogicalId on the L1 resource (((CfnBucket)bucket.Node.DefaultChild!).OverrideLogicalId("AuditBucketB01E0AE8")) to keep the old logical ID while using the new construct id, then confirm that cdk diff shows no changes.
Knowledge check
Answer: At synthesis time only, on your machine or build agent. CloudFormation never sees your C#, only the generated template. This is why loops and conditions in C# are not conditions in the deployed stack.
Answer: The scope (parent construct), the id (unique among siblings, and part of the logical ID) and the props (settings).
Answer: The CDK needs a place for assets (Lambda code, container images) and roles for deployment. Bootstrapping creates the CDKToolkit stack with a bucket, an ECR repository and IAM roles once per account and Region.
Answer: It enables a new behaviour that would change existing templates. Projects created with cdk init get the recommended flags; hand-written cdk.json files get legacy behaviour for flags that are not set, which can produce errors such as the log-bucket ACL conflict.
Answer: The id is part of the path that produces the logical ID. A new logical ID means CloudFormation creates a new resource and deletes (or orphans, with Retain) the old one.
Interview questions
- "CDK or CloudFormation YAML?" The CDK for anything with reuse, loops or a developer-heavy team, because you get types, tests and constructs. YAML for small, static templates and for teams without Node in the toolchain. Either way, the output is reviewed as a template.
- "How do you stop a CDK refactor from deleting a database?"
RemovalPolicy.RETAINorSNAPSHOT, termination protection, a mandatorycdk diffin the pull request, and keeping construct ids stable (or usingOverrideLogicalId). - "What is synthesis?" Running the app to produce CloudFormation templates and assets in
cdk.out. - "Why does a .NET team need Node.js for the CDK?" The construct library is written in TypeScript; .NET calls it through jsii, which starts a Node process.
Certification practice
A team uses the AWS CDK in C#. Before deploying to production they want to see exactly which resources and IAM statements will change. Which command provides this?
A. cdk synth
B. cdk diff
C. cdk bootstrap
D. cdk ls
Answer: B. cdk diff compares the synthesized template with the deployed stack and shows resource and IAM statement changes. cdk synth only produces the template. cdk bootstrap prepares the account. cdk ls lists stacks.
A CDK deployment to a new account fails with an error that the stack uses assets and the toolkit stack must be deployed. What should the operator do?
A. Disable assets in cdk.json.
B. Run cdk bootstrap for that account and Region.
C. Increase the CloudFormation template size limit.
D. Delete cdk.out and retry.
Answer: B. Assets need the bootstrap resources (S3 bucket, ECR repository, roles). A and C are not options. D does not create the missing resources.
A bank wants developers to define infrastructure with familiar languages, reuse approved patterns as packages, and keep AWS managing deployment state. Which fits best?
A. Terraform with local state files. B. AWS CDK, which synthesizes CloudFormation templates deployed by CloudFormation. C. Hand-written shell scripts calling the AWS CLI. D. Manual console configuration with screenshots as evidence.
Answer: B. The CDK provides programming languages and reusable constructs, and CloudFormation holds the state. A needs a state file you manage and is not language-based. C and D are imperative and unreviewable.
Completion checklist
- I installed Node.js, the CDK CLI and bootstrapped the sandbox account
- I synthesized, diffed and deployed the stack and read the template
- I can explain the construct tree and why ids matter
- I can explain what a feature flag does
- I ran
cdk destroyand confirmed nothing is still billing
Key takeaways
- The CDK is C# that generates CloudFormation at synthesis time; CloudFormation does the deploying.
- Scope, id and props: every construct, every time. The id is part of the logical ID.
cdk diffis the review tool; read it like a pull request.- Feature flags in
cdk.jsonchange generated templates. Start fromcdk initand treat flag changes as upgrades. - Always read the synthesized output: abstractions can create resources you did not ask for.
Related lessons and next steps
- Previous: Drift detection and StackSets
- Next: CDK constructs: L1, L2 and L3
- Then: CDK stacks, environments and configuration and Testing CDK
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.
Drift detection and StackSets
Find out when someone has changed a deployed resource outside code, report it with a tested C# tool, fix it safely with drift-aware change sets, and design a StackSet that rolls a security baseline out to every account and Region.
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.