Skip to Content
Cloud Engineering Academy
10. Infrastructure as 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.

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

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

Learning objectives

By the end of this lesson you can:

  • Decide how many stacks an application needs and where to cut them (lifecycle, ownership, blast radius, the 500-resource limit).
  • Pass values between stacks as C# references, and explain the CloudFormation exports and imports the CDK writes for you.
  • Recognise and fix the cross-stack dependency cycle caused by grants and resource policies.
  • Model dev, test and prod as typed settings read from context, validated at synthesis time.
  • Choose between context, Env, Stages and Parameter Store for configuration, and say what belongs in code and what does not.
  • Explain what cdk bootstrap creates, and how to narrow it for a bank.
  • Map each idea to Terraform: variable files, backends per environment, and remote state.

Prerequisites

  • CDK constructs: L1, L2 and L3
  • AWS CDK in C#: your first stack
  • The Module 10 lab code in labs/m10-environment-two-tools is the worked example for this lesson. You only read and synthesize it here; deploying is the lab.
  • Tools: .NET 10 SDK, Node.js 22 or 24 LTS. No AWS account is needed to follow the synthesis steps.

Why this matters in banking

A bank promotes the same reviewed code through dev, test, pre-production and production. The auditor's question is "is what you tested what you released?" If environments are separate copies of code, the answer is "we hope so". If they are one codebase with different settings, the answer is "yes, and here is the diff of settings".

Configuration is also where mistakes become incidents: a production flag left at its dev value (single-AZ database, no deletion protection, seven-day log retention) is a regulatory finding, not a typo. So configuration must be typed, validated before deployment, and reviewed like code.

The idea in plain language

An application is not one stack. You cut it into stacks by how often things change and who owns them:

StackChangesContainsWhy separate
FoundationRarelyNetwork, encryption key, image registryA mistake here is costly, and you want a slow, careful review
ApplicationEvery releaseLoad balancer, service, database, alarmsFast, frequent deployments should not touch the network

Environments (dev, test, prod) are copies of the same stacks with different settings. Settings are plain values in a typed class: how many tasks, whether the database is multi-AZ, how long logs are kept.

Analogy: the stacks are the building's floors: the foundation is poured once, the offices are refitted often. The settings are the occupancy permit: same building plan, but a production branch has more fire exits and a longer inspection schedule than a pilot branch.

What problem this solves

ProblemApproach
One giant stack: slow updates, big blast radius, 500-resource limitSeveral stacks by lifecycle
Copy-pasted code per environmentOne codebase, typed settings per environment
Settings mistakes found in productionValidation at synthesis time and unit tests on the profiles
Hard-coded account IDs and RegionsRead from the CLI environment and context
Stacks entangled by exportsTyped references, explicit dependency, or loose coupling through Parameter Store

Honest limits

  • More stacks means more ordering. Foundation must exist before the application. The CDK works out the order for references, but you still deploy in the right sequence with --all or by name.
  • Cross-stack references create hard coupling (CloudFormation exports). You cannot change or remove an export while another stack imports it.
  • Grants across stacks can create dependency cycles (see below). This is the most common advanced CDK error.
  • Context is not secret storage. cdk.json is committed to Git.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
appsettings.{Environment}.jsonTyped settings from CDK context or a settings fileValidated at synthesis, before any deployment
ARM parameter files per environment-c key=value or a settings class per environmentThe type system is the schema
Azure DevOps environments with approvalsPipeline stages with manual approval (Module 9)The CDK models each environment as a Stage
Bicep targetScope and subscription deploymentsCDK Env (account and Region) per stackA stack is pinned to one account and Region
Deployment slotsNot a CDK concept; use ECS deployment strategiesDifferent problem
Key Vault references in App Service settingsSecrets Manager references in ECS task definitionsThe value never appears in the template

Architecture

The lab's two stacks and the settings that drive them:

Security-boundary view. The settings class is the only place environment differences exist, so a reviewer can read one file to know what production changes. Validation refuses unsafe values before deployment (0.0.0.0/0 for the load balancer, the placeholder owner, an image tag of latest). The foundation stack holds the key; the application stack receives only the key's ARN, not the object, which keeps IAM grants on the roles that use the key.

Stacks in an app and in a Stage

Step-by-step implementation

Read the settings model

Open labs/m10-environment-two-tools/infra/cdk/Harbourline.Environment.Cdk/EnvironmentSettings.cs. It has two records: EnvironmentProfile (what differs per environment) and EnvironmentSettings (the deploy-time inputs).

Synthesize dev and prod and compare

cd labs/m10-environment-two-tools/infra/cdk
cdk synth hl-m10-cdk-dev-foundation  -c owner=<you> > /tmp/dev.yaml
cdk synth hl-m10-cdk-prod-foundation -c owner=<you> -c environmentName=prod > /tmp/prod.yaml
diff /tmp/dev.yaml /tmp/prod.yaml

You see exactly what "prod" changes: key retention, termination protection, log retention.

Run the settings tests

The settings and profile tests are plain C# (no Node.js needed):

cd labs/m10-environment-two-tools
dotnet test --solution EnvironmentTwoTools.slnx

Break a setting on purpose

Pass -c allowedIngressCidr=0.0.0.0/0 -c imageTag=1.0.0 -c owner=<you> and synthesize the app stack. Synthesis fails before anything is deployed, with a message that tells you what to change.

Add a stage

Wrap your stacks in a Stage so the same code produces Dev- and Prod- stacks (code below).

AWS Console instructions

Nothing is deployed in this lesson. To see what bootstrapping created in an account you have bootstrapped: Console → CloudFormation → Stacks → CDKToolkit → Resources lists the staging bucket, the ECR repository and the IAM roles. Console → Systems Manager → Parameter Store shows a parameter with the bootstrap version (named with the qualifier, /cdk-bootstrap/<qualifier>/version; ⚠ VERIFY the parameter path for your bootstrap template).

AWS CLI

# what the app contains and in what order stacks would deploy
cdk ls --long -c owner=<you>

# deploy everything the app defines (foundation first, because the app stack depends on it)
cdk deploy --all -c owner=<you> -c imageTag=<tag> -c allowedIngressCidr=<ip>/32 --profile learn-sandbox

# bootstrap with an explicit qualifier and a narrower execution policy
cdk bootstrap aws://<account>/us-east-1 --profile learn-sandbox \
  --qualifier hlm10 --toolkit-stack-name CDKToolkit-hlm10 \
  --cloudformation-execution-policies arn:aws:iam::<account>:policy/HarbourlineCdkExecution

⚠ VERIFY the bootstrap options against cdk bootstrap --help for your CLI version. Other options commonly used by banks include --trust (accounts that may deploy into this one, for pipelines), --trust-for-lookup, and --termination-protection.

Infrastructure as Code

The settings model (C#)

The lab keeps every environment difference in one record. The code is identical in every environment; only these values differ:

public sealed record EnvironmentProfile
{
    public required string Name { get; init; }
    public required int DesiredCount { get; init; }
    public required int TaskCpu { get; init; }          // Fargate CPU units: 256 = 0.25 vCPU
    public required int TaskMemoryMiB { get; init; }
    public required bool DatabaseMultiAz { get; init; }
    public required bool DeletionProtection { get; init; }
    public required int BackupRetentionDays { get; init; }
    public required int LogRetentionDays { get; init; }
    public required bool RetainDataOnDelete { get; init; }

    public static EnvironmentProfile For(string environmentName) => environmentName switch
    {
        "dev" => new()
        {
            Name = "dev", DesiredCount = 1, TaskCpu = 256, TaskMemoryMiB = 512,
            DatabaseMultiAz = false, DeletionProtection = false, BackupRetentionDays = 1,
            LogRetentionDays = 7, RetainDataOnDelete = false,
        },
        "prod" => new()
        {
            Name = "prod", DesiredCount = 2, TaskCpu = 512, TaskMemoryMiB = 1024,
            DatabaseMultiAz = true, DeletionProtection = true, BackupRetentionDays = 14,
            LogRetentionDays = 90, RetainDataOnDelete = true,
        },
        // "test" omitted here for space; it sits between dev and prod in the lab code
        _ => throw new InvalidOperationException($"Unknown environmentName '{environmentName}'. Use dev, test or prod."),
    };
}

A switch expression returns a complete record or throws, so an unknown environment name is an error on the laptop. The required keyword forces every profile to set every value; adding a new setting breaks the build until each environment decides.

EnvironmentSettings.FromContext(app.Node) reads the deploy-time inputs from cdk.json and -c key=value, and ValidateForAppStack() rejects unsafe or missing values. The two lines that matter most:

// Fail at synth time, on the laptop, instead of half-way through a deployment.
if (prefixLength < 16)
    throw new InvalidOperationException($"allowedIngressCidr {AllowedIngressCidr} is too wide. The lab load balancer is never open to the whole internet.");

if (string.IsNullOrWhiteSpace(ImageTag) || ImageTag == "latest")
    throw new InvalidOperationException("Set -c imageTag=<tag you pushed>. 'latest' is not allowed: tags are immutable.");

Building the stacks for one environment

HarbourlineApp.Build is called both by Program.cs and by the tests, so the tests check what cdk synth produces:

public static (FoundationStack Foundation, AppStack? App) Build(App app, EnvironmentSettings settings)
{
    // Region only: the account comes from the CLI profile at deploy time.
    var env = new Amazon.CDK.Environment { Region = settings.Region };

    var foundation = new FoundationStack(app, $"{settings.NamePrefix}-foundation", new FoundationStackProps
    {
        Settings = settings,
        Env = env,
        TerminationProtection = settings.Profile.RetainDataOnDelete, // prod stacks refuse DeleteStack
    });

    AppStack? appStack = null;
    if (!string.IsNullOrWhiteSpace(settings.ImageTag))
    {
        settings.ValidateForAppStack();
        appStack = new AppStack(app, $"{settings.NamePrefix}-app", new AppStackProps
        {
            Settings = settings,
            Env = env,
            Vpc = foundation.Network.Vpc,       // typed references: the CDK creates the exports and imports
            DataKey = foundation.DataKey,
            Repository = foundation.Repository,
            TerminationProtection = settings.Profile.RetainDataOnDelete,
        });
        appStack.AddStackDependency(foundation); // deploy foundation first
    }

    Tagging.Apply(app, settings);
    return (foundation, appStack);
}

The image tag is empty on the first deployment, so only the foundation stack exists: you push the container image to the foundation's ECR repository, then deploy the application stack with -c imageTag=<tag>. That is a useful pattern whenever one stack produces something another stack consumes.

Stages. A Stage is a deployable copy of a set of stacks. It prefixes stack names (Dev-Evidence, Prod-Evidence) and gives each copy its own Env. CDK Pipelines uses stages as the unit of promotion.

using Amazon.CDK;
using Constructs;

public sealed class EnvironmentStage : Stage
{
    public EnvironmentStage(Construct scope, string id, string environmentName, IStageProps props)
        : base(scope, id, props)
    {
        _ = new EvidenceStack(this, "Evidence", new EvidenceStackProps { EnvironmentName = environmentName });
    }
}

// In Program.cs
var app = new App();
_ = new EnvironmentStage(app, "Dev", "dev",
    new StageProps { Env = new Amazon.CDK.Environment { Account = devAccount, Region = "us-east-1" } });
_ = new EnvironmentStage(app, "Prod", "prod",
    new StageProps { Env = new Amazon.CDK.Environment { Account = prodAccount, Region = "us-east-1" } });
app.Synth();

The account IDs come from your settings file, not from literals scattered in code.

Loose coupling with Parameter Store. Instead of a CloudFormation export, the producer writes a value to Parameter Store and the consumer reads it at deployment:

// Producer
_ = new StringParameter(this, "DataKeyArn", new StringParameterProps
{
    ParameterName = "/harbourline/dev/data-key-arn",
    StringValue = key.KeyArn,
});

// Consumer (a different stack, possibly a different team)
var keyArn = StringParameter.ValueForStringParameter(this, "/harbourline/dev/data-key-arn");
IKey key = Key.FromKeyArn(this, "DataKeyRef", keyArn);

This creates no hard dependency: either stack can be changed or deleted independently (the consumer simply fails if the parameter is missing). Both snippets were compiled with Amazon.CDK.Lib 2.277.0.

Cross-stack references and the dependency cycle

When you pass foundation.Network.Vpc into the application stack, the CDK does three things for you:

  1. In the foundation template it adds an output with an export (for example hl-m10-cdk-dev-foundation:ExportsOutputRef...).
  2. In the application template it replaces the reference with Fn::ImportValue.
  3. It adds a stack dependency so the foundation deploys first.

This is convenient, and it comes with the exports' rule: you cannot change or delete an exported value while it is imported. If you remove a reference to a foundation resource from the app stack and redeploy both stacks, CloudFormation may refuse to update the foundation because the old app stack version still imports the value (the "deadly embrace"). The CDK method ExportValue on the foundation stack keeps an export alive deliberately while you migrate consumers ⚠ VERIFY usage for your version.

The cycle that bit the lab

The lab hit the nastier problem: a cycle. The Module 10 code review found it only when the unit tests ran with Node.js installed (the tests skip silently without Node, a lesson in itself). The symptom:

DependencyCycle: 'hl-m10-cdk-dev-app' depends on 'hl-m10-cdk-dev-foundation' ...
Adding this dependency (hl-m10-cdk-dev-foundation -> hl-m10-cdk-dev-app/Task/ExecutionRole/Resource.Arn)
would create a cyclic reference.

The cause: the application stack's ECS execution role must decrypt the database secret, which is encrypted with the foundation's KMS key. When you pass the real Key object across stacks, the CDK writes the grant into the key policy (a resource policy that lives in the foundation stack). The key policy now names the application's role ARN, so the foundation depends on the application, which already depends on the foundation: a cycle.

Two fixes, and the lab uses both for different resources:

// 1. Import the key by ARN. An imported key cannot be edited, so the CDK puts the
//    grant on the ROLE (an identity policy in the app stack) instead of the key policy.
IKey dataKey = Key.FromKeyArn(this, "DataKeyRef", props.DataKey.KeyArn);

// 2. Same idea for the ECR repository, re-imported by its attributes:
var repository = Repository.FromRepositoryAttributes(this, "Repository", new RepositoryAttributes
{
    RepositoryArn = props.Repository.RepositoryArn,
    RepositoryName = props.Repository.RepositoryName,
});

The foundation key policy already trusts IAM in the account (and allows CloudWatch Logs and alarms for this account only), so an identity policy on the role is sufficient. The general rules:

  • Resource policies live with the resource. A grant that has to edit a resource policy creates a dependency on the stack that owns the resource.
  • Prefer identity-policy grants across stacks: import the resource by ARN or attributes in the consumer.
  • Or keep the resource and its consumers in one stack if they change together.
  • Or decouple with Parameter Store and import by ARN from the parameter value.

Environments, accounts and bootstrapping

Env: environment-agnostic or specific

SettingMeaningUse when
No EnvThe stack can deploy anywhere; account and Region are tokens at synthesisLibraries and tests; no lookups allowed
Env with Region only (the lab)Region fixed; account from the CLI profileA learning lab where the account must not be in Git
Env with account and RegionFully specifiedProduction pipelines, lookups (Vpc.FromLookup), cross-account grants

Concrete accounts make some features possible (context lookups, deterministic ARNs, cross-account grants). The CDK CLI sets CDK_DEFAULT_ACCOUNT and CDK_DEFAULT_REGION from your profile, which keeps account IDs out of source for a lab. In a bank's pipeline repository the account IDs usually are in configuration, reviewed like everything else; account IDs are not secrets.

What cdk bootstrap creates

Bootstrapping deploys a stack, CDKToolkit by default, into each account and Region you deploy to. It contains:

ResourcePurpose
S3 staging bucketStores file assets (Lambda code, templates)
ECR repositoryStores container image assets
IAM rolesA deploy role, a file-publishing role, an image-publishing role, a lookup role, and a CloudFormation execution role
A version parameterLets the CLI check that the bootstrap stack is new enough

The CLI assumes the deploy role, which passes the CloudFormation execution role to CloudFormation. By default the execution role has administrator-level permission, so that any construct works. For a bank, that is the main thing to change.

⚠ Learning shortcut — not for production

The lab bootstraps with the default execution policy and deploys from your laptop. In production you bootstrap each account with a custom execution policy that allows only the services your platform uses (and denies the ability to disable logging or delete the audit bucket), you restrict who may assume the deploy role with --trust to the pipeline account, you enable termination protection on the bootstrap stack, and a pipeline, not a person, runs cdk deploy. ⚠ VERIFY the exact option names with cdk bootstrap --help.

A qualifier (default value hnb659fds in current templates ⚠ VERIFY) is part of every bootstrap resource name. Use a distinct qualifier when two toolkits (for example a platform team's and an app team's) must live in one account, and set the same qualifier in the app so it looks for the right roles.

Complete code

The complete working example for this lesson is the lab, built and tested:

  • labs/m10-environment-two-tools/infra/cdk/Harbourline.Environment.Cdk/EnvironmentSettings.cs (profiles, context, validation)
  • .../HarbourlineApp.cs (builds the stacks for one environment)
  • .../FoundationStack.cs and .../AppStack.cs (the two stacks)
  • .../Program.cs (entry point)
  • labs/m10-environment-two-tools/tests/Harbourline.Environment.Cdk.Tests/SettingsTests.cs (pure C# tests)

The settings tests show how to prove "environments differ only in configuration":

[Theory]
[InlineData("dev", 1, false, false)]
[InlineData("test", 1, false, false)]
[InlineData("prod", 2, true, true)]
public void Profiles_differ_only_in_configuration(string name, int desired, bool multiAz, bool protect)
{
    var p = EnvironmentProfile.For(name);
    Assert.Equal(desired, p.DesiredCount);
    Assert.Equal(multiAz, p.DatabaseMultiAz);
    Assert.Equal(protect, p.DeletionProtection);
    Assert.Equal(protect, p.RetainDataOnDelete);
}

[Theory]
[InlineData("0.0.0.0/0")]
[InlineData("10.0.0.0/8")]
[InlineData("")]
[InlineData("not-an-ip/32")]
public void Wide_or_malformed_ingress_ranges_are_refused(string cidr)
{
    Assert.Throws<InvalidOperationException>(() => (Valid with { AllowedIngressCidr = cidr }).ValidateForAppStack());
}

Code explained line by line

  1. sealed record EnvironmentProfile with required members. An immutable value object. required makes the compiler enforce that every profile sets every field, so adding a setting forces a decision for each environment.
  2. switch expression in For(...). Exhaustive by construction: the default arm throws. Compare with an if chain that silently falls through to dev settings in production.
  3. TerminationProtection = settings.Profile.RetainDataOnDelete. A property of the stack (not a resource) that makes DeleteStack fail. Tied to the profile so prod is protected automatically.
  4. Vpc = foundation.Network.Vpc. A C# reference to an object in another stack. At synthesis the CDK turns it into an export and an Fn::ImportValue. The compiler checks the type (Vpc), which YAML never could.
  5. appStack.AddStackDependency(foundation). Explicit ordering. References create dependencies automatically; this line documents the intent and also covers resources that depend on side effects (for example an image existing in the registry).
  6. Key.FromKeyArn(...). Turns a real construct into an imported reference. It breaks the object link on purpose, so grants go to the role instead of the key policy.
  7. ImageTag.Empty branch. Only the foundation is created when no image tag is given. The unit tests set a tag so both stacks synthesize.
  8. Tagging.Apply(app, settings). Tags are added once at the app level, after the stacks exist, and flow to every taggable resource.
  9. Stage. Wraps a whole set of stacks so they can be instantiated several times in one app, each with its own Env, and each stack name prefixed with the stage id.

Security considerations

  • No secrets in settings or context. The database password in the lab never appears in code: RDS generates it into Secrets Manager, and the task definition references it. cdk.json can be committed safely.
  • Validate before you deploy. A wide CIDR or a missing owner tag fails on the laptop. Add the same checks as unit tests so a pipeline catches them.
  • Production differences are security controls. Multi-AZ, deletion protection, termination protection, longer retention and RETAIN are the production profile. Review changes to the profile with the security team.
  • Separate accounts for environments. Stages with different accounts give hard isolation. Keep production state and deploy roles in the production account or a tooling account.
  • Narrow the bootstrap execution policy and restrict --trust to the pipeline account, as described above.
  • Grants across stacks are IAM changes. Read the IAM statement table in cdk diff for every cross-stack change.
  • Regions and residency. Put the Region in reviewed configuration. UK and EU data residency is decided by the data owner, not by whoever edited the default (see UK GDPR and data residency).

Banking use case

Harbourline runs the Accounts API in three accounts: workloads-dev, workloads-test and workloads-prod. One repository holds the CDK app; settings/dev.json, settings/test.json and settings/prod.json hold the values. A pull request that changes prod.json needs the platform lead and a security reviewer (CODEOWNERS), and the pipeline posts cdk diff for prod into the pull request. The same Git commit builds the container image, deploys to dev, then test, then waits for a manual approval before prod. When the auditor asks "is test the same as prod?", the answer is the diff of the three settings files.

Common mistakes

  • Cutting stacks by AWS service (a "database stack", a "network stack") rather than by lifecycle and ownership.
  • Exporting everything, then being unable to change anything. Pass only what consumers need.
  • Passing real constructs that need resource-policy changes across stacks (keys, repositories, queues, buckets) and meeting a cycle. Import by ARN in the consumer, or co-locate.
  • Hard-coding account IDs in construct code instead of settings.
  • Defaults that are production-unsafe, so a missing setting silently deploys dev behaviour to prod. Make production-relevant settings required.
  • Skipping validation and discovering an invalid CIDR in a CloudFormation error twenty minutes into a deployment.
  • Bootstrapping with the default policy in production and never narrowing it.
  • Forgetting that tests skip without Node.js. A green build with 28 skipped tests proved nothing: run the tests with Node installed in CI and fail the build on skips.

Troubleshooting

SymptomLikely causeFix
DependencyCycle: ... would create a cyclic referenceA grant wrote a resource policy in the producer stack that names a consumer resourceImport the resource by ARN or attributes in the consumer, or co-locate
Export ... cannot be updated as it is in use by ...A consumer still imports the valueDeploy the consumer without the reference first, or keep the export with ExportValue while migrating
Unknown environmentName 'staging'A name not in EnvironmentProfile.ForUse dev, test or prod, or add a profile deliberately
Set -c allowedIngressCidr=...Validation rejected the CIDRUse your public IP as /32
Need to perform AWS calls for account ... but no credentials foundA lookup (FromLookup) needs a concrete account and credentialsProvide Env with the account and sign in
SSM parameter ... not found at deployThe consumer deployed before the producerDeploy the producer stack first, or add a dependency
Resolution error: Cannot use resource ... in a cross-environment fashionReferencing a resource in a stack with a different account or RegionSet explicit Env, and use CrossRegionReferences = true or Parameter Store
Stage stack names have an unexpected prefixStages prefix stack ids with the stage idReference stacks by the full name in cdk deploy
28 tests skipped in CINode.js missing on the build agentInstall Node 22 or 24 LTS on the agent

Cost and cleanup

Cost: free. Everything in this lesson is local synthesis and unit tests. If you bootstrapped an account earlier, the CDKToolkit stack costs cents per month (the staging bucket and ECR repository) and is shared by all CDK labs.

# remove generated output; nothing is deployed
rm -rf cdk.out /tmp/dev.yaml /tmp/prod.yaml

Exercises

  • 🟢 Guided: synthesize the foundation for dev and prod, diff the two outputs, and list every difference. Then run the settings tests.
  • 🟡 Challenge: add a Staging environment to EnvironmentProfile.For between test and prod (multi-AZ database, 30-day log retention, no data retention on delete). Add the InlineData row to the profile test first, watch it fail, then implement.
  • 🔴 Live problem: your CDK app has an ApiStack that takes a Bucket from a StorageStack and calls bucket.GrantRead(taskRole). After a refactor cdk synth reports a dependency cycle. Explain why, give two fixes, and say which you would choose if both stacks are owned by different teams.

Assignment

Write docs/environments.md in your portfolio repository: a table of dev, test and prod settings (copy the profile), who approves changes to each, how a change is promoted, which account each runs in, and what the bootstrap execution policy allows. Attach the output of diff dev.yaml prod.yaml from your synthesis.

Solutions

Knowledge check

Interview questions

  • "How do you promote the same CDK code through dev, test and prod?" One codebase, typed settings per environment, validated and unit-tested; Stages (or separate stack names) per environment and account; a pipeline that deploys in order with approvals; the settings diff as the review artefact.
  • "What is a cross-stack cycle and how do you fix it?" A mutual dependency created when a grant edits a resource policy in another stack. Import the resource by ARN in the consumer, co-locate, or decouple with Parameter Store.
  • "What does cdk bootstrap create and what would you change for production?" A staging bucket, ECR repository and IAM roles. Narrow the CloudFormation execution policy, restrict trust to the pipeline account, protect the stack and use a qualifier to avoid clashes.
  • "Where do secrets go?" Never in context or settings. Secrets Manager or Parameter Store references resolved at runtime by the service.

Certification practice

Completion checklist

  • I can explain where to cut stacks and why
  • I synthesized dev and prod and listed the differences
  • I can explain the exports the CDK creates and why they couple stacks
  • I can explain the key-policy dependency cycle and two fixes
  • I know what cdk bootstrap creates and what I would narrow for production

Key takeaways

  • Cut stacks by lifecycle and ownership; keep environments as typed settings over one codebase.
  • Validate settings at synthesis; production-relevant differences are controls.
  • References across stacks become exports; grants that edit resource policies can create cycles. Import by ARN in the consumer.
  • Bootstrapping creates roles that deploy for you: narrow the execution policy in a bank.
  • Tests that silently skip prove nothing: run them with Node.js in CI.

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