Skip to Content
Cloud Engineering Academy
10. Infrastructure as Code

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.

intermediate⏱ 2 h 30 min🟡 Low costDOP-C02SOA-C03

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 diff and cdk deploy, and read each output.
  • Explain feature flags in cdk.json and 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 the learn-sandbox profile.

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:

TermMeaning
AppThe root object. One per program (new App())
StackA unit of deployment. One stack becomes one CloudFormation stack
ConstructAny 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 templatesCDK answer
No types: a typo in a property name is found at deploy timeThe C# compiler finds it
Copy-paste reuseClasses and NuGet packages
IAM policies written by handbucket.GrantRead(role) writes the policy statement
Hard to testxUnit tests over the synthesized template (Testing CDK)
Defaults you must rememberL2 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 diff after upgrades.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
BicepAWS CDKBicep 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 synthBoth produce the deployable template
az deployment what-ifcdk diffcdk diff also highlights IAM and security group changes
NuGet package of Azure resourcesNuGet packages Amazon.CDK.Lib and your own construct libraryOne big package holds all stable AWS constructs
az bicep modulesConstructsA 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.x

The 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-sandbox

You 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-sandbox

Change 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-sandbox

AWS 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 table

What 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
cdk.json
{
  "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
  }
}
Harbourline.Evidence.Cdk.csproj
<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>
Program.cs
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();
EvidenceStack.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;

/// <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

  1. new App(). The root of the tree. With no arguments it writes the cloud assembly to cdk.out/ (the CLI sets the output folder through an environment variable).
  2. app.Node.TryGetContext("owner"). Context is a bag of key/value settings from cdk.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.
  3. new Amazon.CDK.Environment { ... }. The full name is needed because plain Environment is ambiguous with System.Environment in C#. When the account is null and 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_ACCOUNT is filled in by the CLI.
  4. Tags.Of(app).Add(...). A tag added at the app level is applied to every taggable resource below. The Amazon.CDK.Tags class is available in a top-level program. Inside a Stack subclass you must write Amazon.CDK.Tags.Of(this) because Tags resolves to the stack's own Tags property (compile error CS0176).
  5. EvidenceStackProps : StackProps. The required C# keyword makes the compiler refuse an EvidenceStackProps without EnvironmentName. This is the main reason to prefer a CDK app over YAML for shared stacks.
  6. RemovalPolicy. The CDK's name for DeletionPolicy plus UpdateReplacePolicy. DESTROY becomes Delete, RETAIN becomes Retain. Dev and test are disposable, prod is not.
  7. 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.
  8. 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 requires RemovalPolicy.DESTROY and the bootstrap stack.
  9. BucketKeyEnabled = true. Reduces KMS requests, as in the CloudFormation lesson.
  10. ServerAccessLogsBucket = logs. The CDK adds the bucket policy that lets the S3 logging service write. This is where the feature flag matters, see below.
  11. LifecycleRules = [ ... ]. C# 12 collection expressions fill the array type that jsii expects.
  12. AuditBucket.AddToResourcePolicy(...). Adds a statement to the bucket policy. ArnForObjects("*") builds the object ARN pattern. This is imperative code generating a declarative statement; the if (isProd) exists only at synthesis time, and the dev template simply does not contain the statement.
  13. CfnOutput. Becomes an Outputs entry. Property names stay as properties so tests can read AuditBucket and DataKey.

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.json is committed to Git. Put only non-secret settings there.
  • cdk deploy prompts when permissions broaden. Do not disable --require-approval in pipelines without another gate such as a reviewed cdk diff.
  • Pin versions. Amazon.CDK.Lib 2.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-1 in 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 diff and look for [-] plus [+] pairs.
  • Writing C# conditions that depend on deploy-time values. Values such as bucket.BucketName are 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.json or editing flags without a diff.
  • Using Amazon.CDK.Tags.Of(this) inside a stack without the Amazon.CDK. prefix (error CS0176).
  • Adding an explicit Constructs package reference with an older version than Amazon.CDK.Lib needs. NuGet reports a downgrade error (NU1605). Reference only Amazon.CDK.Lib; it brings Constructs with it.

Troubleshooting

SymptomLikely causeFix
Unable to find ... node or the app hangs at startNode.js missing or too oldInstall Node.js 22 or 24 LTS and open a new terminal
Node warns that your Node version is end-of-lifeOld Node (for example 18)Upgrade to a supported LTS release
objectOwnership must be set to "ObjectWriter"...Missing serverAccessLogsUseBucketPolicy flagAdd the flag to cdk.json context (see above)
This stack uses assets, so the toolkit stack must be deployedAccount not bootstrappedcdk bootstrap aws://<account>/us-east-1 --profile learn-sandbox
Need to perform AWS calls for account ... but no credentials foundSSO session expired or no --profileaws sso login --profile learn-sandbox and pass --profile
Set -c owner=<your-name> ...The guard in Program.csAdd -c owner=<your-name>
NU1605 package downgradeExplicit Constructs reference older than the library'sRemove the explicit reference
CS0176 on Amazon.CDK.Tags.Of(this)Tags resolves to the stack's propertyAmazon.CDK.Tags.Of(this)
AWS::S3::Bucket ... already existsA retained bucket from another run has the same nameLet the CDK generate names (as here) instead of fixed bucket names
cdk diff shows more than you changedLibrary or flag changeRead 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, find AuditBucketB01E0AE8 in the template, deploy, read the outputs, change NoncurrentVersionDays to 120 and read the diff, then destroy.
  • 🟡 Challenge: add an AccessLogRetentionDays property to EvidenceStackProps (default 90) and use it for the log bucket's expiration. Run cdk diff to confirm that the default produces no change to the deployed stack.
  • 🔴 Live problem: a colleague renamed the construct id AuditBucket to EvidenceBucket in a pull request and wrote "refactor only, no functional change". The stack is prod with RETAIN. Explain what cdk diff will 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

Knowledge check

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.RETAIN or SNAPSHOT, termination protection, a mandatory cdk diff in the pull request, and keeping construct ids stable (or using OverrideLogicalId).
  • "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

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 destroy and 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 diff is the review tool; read it like a pull request.
  • Feature flags in cdk.json change generated templates. Start from cdk init and treat flag changes as upgrades.
  • Always read the synthesized output: abstractions can create resources you did not ask for.

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