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.
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 bootstrapcreates, 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-toolsis 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:
| Stack | Changes | Contains | Why separate |
|---|---|---|---|
| Foundation | Rarely | Network, encryption key, image registry | A mistake here is costly, and you want a slow, careful review |
| Application | Every release | Load balancer, service, database, alarms | Fast, 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
| Problem | Approach |
|---|---|
| One giant stack: slow updates, big blast radius, 500-resource limit | Several stacks by lifecycle |
| Copy-pasted code per environment | One codebase, typed settings per environment |
| Settings mistakes found in production | Validation at synthesis time and unit tests on the profiles |
| Hard-coded account IDs and Regions | Read from the CLI environment and context |
| Stacks entangled by exports | Typed 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
--allor 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.jsonis committed to Git.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
appsettings.{Environment}.json | Typed settings from CDK context or a settings file | Validated at synthesis, before any deployment |
| ARM parameter files per environment | -c key=value or a settings class per environment | The type system is the schema |
| Azure DevOps environments with approvals | Pipeline stages with manual approval (Module 9) | The CDK models each environment as a Stage |
Bicep targetScope and subscription deployments | CDK Env (account and Region) per stack | A stack is pinned to one account and Region |
| Deployment slots | Not a CDK concept; use ECS deployment strategies | Different problem |
| Key Vault references in App Service settings | Secrets Manager references in ECS task definitions | The 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.yamlYou 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.slnxBreak 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:
- In the foundation template it adds an output with an export (for example
hl-m10-cdk-dev-foundation:ExportsOutputRef...). - In the application template it replaces the reference with
Fn::ImportValue. - 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
| Setting | Meaning | Use when |
|---|---|---|
No Env | The stack can deploy anywhere; account and Region are tokens at synthesis | Libraries and tests; no lookups allowed |
Env with Region only (the lab) | Region fixed; account from the CLI profile | A learning lab where the account must not be in Git |
Env with account and Region | Fully specified | Production 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:
| Resource | Purpose |
|---|---|
| S3 staging bucket | Stores file assets (Lambda code, templates) |
| ECR repository | Stores container image assets |
| IAM roles | A deploy role, a file-publishing role, an image-publishing role, a lookup role, and a CloudFormation execution role |
| A version parameter | Lets 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.csand.../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
sealed record EnvironmentProfilewithrequiredmembers. An immutable value object.requiredmakes the compiler enforce that every profile sets every field, so adding a setting forces a decision for each environment.switchexpression inFor(...). Exhaustive by construction: the default arm throws. Compare with anifchain that silently falls through to dev settings in production.TerminationProtection = settings.Profile.RetainDataOnDelete. A property of the stack (not a resource) that makesDeleteStackfail. Tied to the profile so prod is protected automatically.Vpc = foundation.Network.Vpc. A C# reference to an object in another stack. At synthesis the CDK turns it into an export and anFn::ImportValue. The compiler checks the type (Vpc), which YAML never could.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).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.ImageTag.Emptybranch. Only the foundation is created when no image tag is given. The unit tests set a tag so both stacks synthesize.Tagging.Apply(app, settings). Tags are added once at the app level, after the stacks exist, and flow to every taggable resource.Stage. Wraps a whole set of stacks so they can be instantiated several times in one app, each with its ownEnv, 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.jsoncan 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
RETAINare 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
--trustto the pipeline account, as described above. - Grants across stacks are IAM changes. Read the IAM statement table in
cdk difffor 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
| Symptom | Likely cause | Fix |
|---|---|---|
DependencyCycle: ... would create a cyclic reference | A grant wrote a resource policy in the producer stack that names a consumer resource | Import 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 value | Deploy the consumer without the reference first, or keep the export with ExportValue while migrating |
Unknown environmentName 'staging' | A name not in EnvironmentProfile.For | Use dev, test or prod, or add a profile deliberately |
Set -c allowedIngressCidr=... | Validation rejected the CIDR | Use your public IP as /32 |
Need to perform AWS calls for account ... but no credentials found | A lookup (FromLookup) needs a concrete account and credentials | Provide Env with the account and sign in |
SSM parameter ... not found at deploy | The consumer deployed before the producer | Deploy the producer stack first, or add a dependency |
Resolution error: Cannot use resource ... in a cross-environment fashion | Referencing a resource in a stack with a different account or Region | Set explicit Env, and use CrossRegionReferences = true or Parameter Store |
| Stage stack names have an unexpected prefix | Stages prefix stack ids with the stage id | Reference stacks by the full name in cdk deploy |
| 28 tests skipped in CI | Node.js missing on the build agent | Install 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.yamlExercises
- 🟢 Guided: synthesize the foundation for dev and prod, diff the two outputs, and list every difference. Then run the settings tests.
- 🟡 Challenge: add a
Stagingenvironment toEnvironmentProfile.Forbetween test and prod (multi-AZ database, 30-day log retention, no data retention on delete). Add theInlineDatarow to the profile test first, watch it fail, then implement. - 🔴 Live problem: your CDK app has an
ApiStackthat takes aBucketfrom aStorageStackand callsbucket.GrantRead(taskRole). After a refactorcdk synthreports 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
Differences you should find between dev and prod foundation templates: the KMS key and ECR repository carry DeletionPolicy: Retain in prod and Delete in dev; the stack has termination protection in prod; flow-log retention is 90 days in prod and 7 in dev; the ECR EmptyOnDelete helper exists only where data is not retained. The settings tests pass without Node.js. The point is that all differences are explained by the profile record.
Add a "staging" arm to the switch with DatabaseMultiAz = true, LogRetentionDays = 30, RetainDataOnDelete = false, DeletionProtection = false (or true, if your team wants staging protected), and add [InlineData("staging", 2, true, false)] to the test. The test fails first with Unknown environmentName 'staging', then passes. Update the validation messages that list environment names, and the NatFreeVpc.ToRetention mapping if you chose a retention that is not already supported (30 is).
GrantRead on a real Bucket from another stack edits the bucket policy (and, for an encrypted bucket, the key policy), which are resources in StorageStack. The policy then references the task role ARN in ApiStack, so storage depends on API while API depends on storage: a cycle. Fixes: (1) in ApiStack import the bucket with Bucket.FromBucketAttributes (name and ARN) so the grant lands in the role's identity policy; (2) move the grant into a small third stack that depends on both; (3) put both resources in one stack. With two teams, choose (1): it keeps ownership boundaries, the storage team publishes name and ARN (output or Parameter Store), and the API team grants itself access, which the storage team can still restrict with a bucket policy condition.
Knowledge check
Answer: An output with an export in the producing template, an Fn::ImportValue in the consuming template, and a stack dependency. Exports cannot be changed or removed while imported.
Answer: The grant is written into the key policy, which belongs to the key's stack, and names the consumer's role. The key's stack then depends on the consumer's stack, which already depends on the key's stack.
Answer: In one typed settings model (records or a settings file) validated at synthesis time and covered by unit tests. The construct code must be identical in every environment.
Answer: The CloudFormation execution role created by bootstrapping. By default it is highly privileged, so banks replace it with a narrower custom policy and restrict who can assume the deploy role.
Answer: A deployable copy of a group of stacks with its own environment and a name prefix, so one codebase can produce dev, test and prod and a pipeline can promote them in order.
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
A team deploys the same AWS CDK app to dev, test and prod accounts. Production must use a multi-AZ database and deletion protection, while dev must not. Which approach best prevents production settings from being used in dev by mistake and vice versa?
A. Maintain three copies of the application code. B. One codebase with a typed environment profile selected by name and validated at synthesis, with unit tests for each profile. C. Edit the template manually before each deployment. D. Use the console to change settings after deployment.
Answer: B. One codebase with validated, tested profiles keeps environments consistent and makes differences reviewable. A and C cause drift and errors. D is unreviewed and unrepeatable.
A CDK app deploys the CDK bootstrap stack in many accounts. Security requires that CloudFormation cannot create arbitrary IAM administrators during CDK deployments. What should the architects do?
A. Remove the bootstrap stack. B. Bootstrap each account with a custom CloudFormation execution policy that grants only the permissions the platform needs. C. Give developers AdministratorAccess so the bootstrap policy does not matter. D. Deploy only from the management account.
Answer: B. The execution policy limits what CloudFormation may create on behalf of CDK deployments. A prevents deployment. C removes the control. D concentrates risk and does not limit CloudFormation's permissions.
A CDK deployment of an application stack fails because CloudFormation reports a circular dependency between the application stack and a shared encryption-key stack after an IAM grant was added. What is the most direct fix?
A. Disable rollback. B. Import the key into the application stack by ARN so the grant is added to the role's identity policy instead of the key policy. C. Increase the stack timeout. D. Create the key in every Region.
Answer: B. An imported key cannot have its policy edited by the consumer, so the grant goes on the role and the cycle disappears. A, C and D do not address the dependency.
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 bootstrapcreates 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.
Related lessons and next steps
- Previous: CDK constructs: L1, L2 and L3
- Next: Testing CDK
- Then: Lab: one environment, two tools
- Later: Environment configuration and versioning
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.
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.
Testing CDK: assertions, snapshots and cdk-nag
Prove infrastructure controls with xUnit tests over the synthesized template, add a coarse snapshot that catches surprise changes, and run cdk-nag v3 as a test with every finding fixed or acknowledged with a written reason.