From 1e0800ac0fe29db62d8356a4e42ec63d3892e371 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carl=20F=C3=BCrstenberg?= Date: Sun, 22 Nov 2026 12:09:24 +0100 Subject: [PATCH 1/3] fix(toolkit-lib): show termination protection changes in diff `cdk diff` only compared templates, so a change to a stack's termination protection was never shown and the stack was reported as unchanged. When diffing against a deployed stack, read the deployed termination protection setting along with the template, and show a difference with the app's setting as a stack property change: Stack Properties [~] TerminationProtection: disabled to enabled The stack is counted as changed. Nothing is compared when diffing against a template file, or when the stack has not been deployed yet. Refs aws/aws-cdk#32043 Co-Authored-By: Claude Opus 5.5 --- .../lib/actions/diff/private/helpers.ts | 1 + .../cloudformation/nested-stack-helpers.ts | 18 ++- .../lib/api/diff/diff-formatter.ts | 59 ++++++++- .../toolkit-lib/test/actions/diff.test.ts | 23 ++++ .../cloudformation-deployments.test.ts | 36 ++++++ .../toolkit-lib/test/api/diff/diff.test.ts | 116 ++++++++++++++++++ packages/aws-cdk/lib/cli/cdk-toolkit.ts | 1 + packages/aws-cdk/test/commands/diff.test.ts | 44 +++++++ 8 files changed, 293 insertions(+), 5 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/actions/diff/private/helpers.ts b/packages/@aws-cdk/toolkit-lib/lib/actions/diff/private/helpers.ts index 94a073e24..5a0261219 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/actions/diff/private/helpers.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/actions/diff/private/helpers.ts @@ -122,6 +122,7 @@ async function cfnDiff( changeSet, mappings, environment, + deployedTerminationProtection: templateWithNestedStacks.deployedTerminationProtection, }); } diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts b/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts index 9b1c0dd96..f2bdf8b99 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts @@ -12,6 +12,13 @@ export interface RootTemplateWithNestedStacks { readonly nestedStacks: { [nestedStackLogicalId: string]: NestedStackTemplates; }; + + /** + * Whether termination protection is enabled on the deployed root stack + * + * @default undefined - the stack does not exist, or the setting was not read + */ + readonly deployedTerminationProtection?: boolean; } /** @@ -22,7 +29,8 @@ export async function loadCurrentTemplateWithNestedStacks( sdk: SDK, retrieveProcessedTemplate: boolean = false, ): Promise { - const deployedRootTemplate = await loadCurrentTemplate(rootStackArtifact, sdk, retrieveProcessedTemplate); + const rootStack = await CloudFormationStack.lookup(sdk.cloudFormation(), rootStackArtifact.stackName, retrieveProcessedTemplate); + const deployedRootTemplate = await rootStack.template(); const nestedStacks = await loadNestedStacks(rootStackArtifact, sdk, { generatedTemplate: rootStackArtifact.template, deployedTemplate: deployedRootTemplate, @@ -32,9 +40,17 @@ export async function loadCurrentTemplateWithNestedStacks( return { deployedRootTemplate, nestedStacks, + deployedTerminationProtection: hasBeenDeployed(rootStack) ? !!rootStack.terminationProtection : undefined, }; } +/** + * Whether the stack exists and is not just a placeholder for a change set that was never executed + */ +function hasBeenDeployed(stack: CloudFormationStack): boolean { + return stack.exists && stack.stackStatus.name !== 'REVIEW_IN_PROGRESS'; +} + /** * Returns the currently deployed template from CloudFormation that corresponds to `stackArtifact`. */ diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts b/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts index c4ac7df60..23314c945 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts @@ -158,6 +158,16 @@ export interface TemplateInfo { * @default undefined - no environment is shown */ readonly environment?: cxapi.Environment; + + /** + * Whether termination protection is enabled on the deployed stack. + * + * If this differs from the termination protection of `newTemplate`, the change is shown as a stack property change. + * Only set this when comparing against a deployed stack. + * + * @default undefined - termination protection is not compared + */ + readonly deployedTerminationProtection?: boolean; } /** @@ -270,9 +280,22 @@ export class DiffFormatter { mappings: this.mappings, logicalIdMap: buildLogicalToPathMap(this.templateInfo.newTemplate).toPath, environmentString: this.environmentString, + terminationProtectionChange: this.terminationProtectionChange(), }, options); } + /** + * The change in termination protection of the root stack, if there is one + */ + private terminationProtectionChange(): TerminationProtectionChange | undefined { + const oldValue = this.templateInfo.deployedTerminationProtection; + const newValue = this.templateInfo.newTemplate.terminationProtection ?? false; + if (oldValue === undefined || oldValue === newValue) { + return undefined; + } + return { oldValue, newValue }; + } + private formatStackDiffHelper(params: { oldTemplate: Template; newTemplate: Template; @@ -283,8 +306,12 @@ export class DiffFormatter { logicalIdMap: Record; // Only set for the root stack; nested stacks share their parent's environment. environmentString?: string; + // Only set for the root stack; termination protection is a property of the root stack. + terminationProtectionChange?: TerminationProtectionChange; }, options: ReusableStackDiffOptions = {}): FormatStackDiffOutput { - const { oldTemplate, newTemplate, stackName, nestedStacks, changeSet, mappings, logicalIdMap, environmentString } = params; + const { + oldTemplate, newTemplate, stackName, nestedStacks, changeSet, mappings, logicalIdMap, environmentString, terminationProtectionChange, + } = params; const diff = this.computeDiff(stackName, oldTemplate, newTemplate, changeSet, mappings); const pathMap = this.recordPaths(stackName, oldTemplate, newTemplate, logicalIdMap); @@ -296,7 +323,7 @@ export class DiffFormatter { try { // must output the stack name if there are differences, even if quiet - if (stackName && (!options.quiet || !diff.isEmpty)) { + if (stackName && (!options.quiet || !diff.isEmpty || terminationProtectionChange)) { stream.write(format(`Stack ${chalk.bold(stackName)}${formatEnvironment(environmentString)}\n`)); } @@ -325,11 +352,17 @@ export class DiffFormatter { } const metadataWasFiltered = diffWasNonEmpty && activeDiff.isEmpty; - if (!activeDiff.isEmpty) { + if (terminationProtectionChange) { + stream.write(formatTerminationProtectionChange(terminationProtectionChange)); + } + + if (!activeDiff.isEmpty || terminationProtectionChange) { numStacksWithChanges++; + } + if (!activeDiff.isEmpty) { formatDifferences(stream, activeDiff, pathMap, options.contextLines); - } else if (!options.quiet) { + } else if (!options.quiet && !terminationProtectionChange) { const hint = metadataWasFiltered ? chalk.grey(' (CDK metadata changes were hidden, run cdk diff --strict to show)') : ''; stream.write(`${chalk.green('There were no differences')}${hint}\n`); } @@ -526,3 +559,21 @@ function annotateMoves(templateDiff: TemplateDiff, stackName: string, mappings: } }); } + +/** + * A change in the termination protection of a stack + */ +interface TerminationProtectionChange { + readonly oldValue: boolean; + readonly newValue: boolean; +} + +function formatTerminationProtectionChange(change: TerminationProtectionChange): string { + const describe = (enabled: boolean) => enabled ? 'enabled' : 'disabled'; + return [ + chalk.underline(chalk.bold('Stack Properties')), + `${chalk.yellow('[~]')} TerminationProtection: ${describe(change.oldValue)} to ${describe(change.newValue)}`, + '', + '', + ].join('\n'); +} diff --git a/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts b/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts index f3063cdad..919a5e7a8 100644 --- a/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts @@ -419,6 +419,29 @@ describe('diff', () => { })); }); + test('shows a change in termination protection of the deployed stack', async () => { + // GIVEN + jest.spyOn(deployments.Deployments.prototype, 'readCurrentTemplateWithNestedStacks').mockResolvedValue({ + deployedRootTemplate: {}, + nestedStacks: {}, + deployedTerminationProtection: true, + }); + + // WHEN + const cx = await cdkOutFixture(toolkit, 'stack-with-bucket'); + await toolkit.diff(cx, { + stacks: { strategy: StackSelectionStrategy.ALL_STACKS }, + method: DiffMethod.TemplateOnly(), + }); + + // THEN + expect(ioHost.notifySpy).toHaveBeenCalledWith(expect.objectContaining({ + action: 'diff', + level: 'result', + message: expect.stringContaining('TerminationProtection: enabled to disabled'), + })); + }); + describe('DiffMethod.ChangeSet', () => { test('ChangeSet diff method falls back to template only if changeset not found', async () => { // WHEN diff --git a/packages/@aws-cdk/toolkit-lib/test/api/deployments/cloudformation-deployments.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/deployments/cloudformation-deployments.test.ts index 36527c312..2e46e776b 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/deployments/cloudformation-deployments.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/deployments/cloudformation-deployments.test.ts @@ -4,6 +4,7 @@ import { DescribeStackEventsCommand, type DescribeStackEventsCommandInput, DescribeStacksCommand, + GetTemplateCommand, ListStackResourcesCommand, RollbackStackCommand, type StackResourceSummary, @@ -405,6 +406,41 @@ test.each([false, true])( }, ); +test.each([ + [true, true], + [false, false], + [undefined, false], +])('readCurrentTemplateWithNestedStacks() returns termination protection %p of the deployed stack as %p', async (enabled, expected) => { + // GIVEN + jest.spyOn(CloudFormationStack, 'lookup').mockImplementation(async (cfn, stackName) => CloudFormationStack.fromStaticInformation(cfn, stackName, { + StackName: stackName, + CreationTime: new Date(), + StackStatus: StackStatus.CREATE_COMPLETE, + EnableTerminationProtection: enabled, + })); + mockCloudFormationClient.on(GetTemplateCommand).resolves({ TemplateBody: '{}' }); + + // WHEN + const result = await deployments.readCurrentTemplateWithNestedStacks(testStack({ stackName: 'boop' })); + + // THEN + expect(result.deployedTerminationProtection).toBe(expected); +}); + +test.each([ + ['does not exist', undefined], + ['has not been deployed yet', StackStatus.REVIEW_IN_PROGRESS], +])('readCurrentTemplateWithNestedStacks() does not return termination protection if the stack %s', async (_, stackStatus) => { + // GIVEN + givenStacks(stackStatus ? { boop: { template: {}, stackStatus } } : {}); + + // WHEN + const result = await deployments.readCurrentTemplateWithNestedStacks(testStack({ stackName: 'boop' })); + + // THEN + expect(result.deployedTerminationProtection).toBeUndefined(); +}); + test('readCurrentTemplateWithNestedStacks() can handle non-Resources in the template', async () => { const stackSummary = stackSummaryOf( 'NestedStack', diff --git a/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts index 49d4d7ec7..53f020d4f 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts @@ -383,6 +383,122 @@ describe('formatStackDiff', () => { }); }); +describe('termination protection', () => { + const template = { + Resources: { + Queue: { Type: 'AWS::SQS::Queue' }, + }, + }; + + function stackArtifact(terminationProtection?: boolean): cxapi.CloudFormationStackArtifact { + return { + template, + templateFile: 'template.json', + stackName: 'test-stack', + terminationProtection, + findMetadataByType: () => [], + } as any; + } + + test('shows enabling termination protection as a stack property change', () => { + // WHEN + const formatter = new DiffFormatter({ + templateInfo: { + oldTemplate: template, + newTemplate: stackArtifact(true), + deployedTerminationProtection: false, + }, + }); + const result = formatter.formatStackDiff(); + + // THEN + expect(result.numStacksWithChanges).toBe(1); + expect(stripAnsi(result.formattedDiff!).trim()).toBe( + 'Stack test-stack\n' + + 'Stack Properties\n' + + '[~] TerminationProtection: disabled to enabled', + ); + }); + + test('treats unset termination protection in the app as disabled', () => { + // WHEN + const formatter = new DiffFormatter({ + templateInfo: { + oldTemplate: template, + newTemplate: stackArtifact(undefined), + deployedTerminationProtection: true, + }, + }); + const result = formatter.formatStackDiff(); + + // THEN + expect(result.numStacksWithChanges).toBe(1); + expect(stripAnsi(result.formattedDiff!)).toContain('[~] TerminationProtection: enabled to disabled'); + }); + + test('shows the stack property change alongside template changes and counts the stack once', () => { + // WHEN + const formatter = new DiffFormatter({ + templateInfo: { + oldTemplate: {}, + newTemplate: stackArtifact(true), + deployedTerminationProtection: false, + }, + }); + const result = formatter.formatStackDiff(); + + // THEN + expect(result.numStacksWithChanges).toBe(1); + expect(stripAnsi(result.formattedDiff!).trim()).toBe( + 'Stack test-stack\n' + + 'Stack Properties\n' + + '[~] TerminationProtection: disabled to enabled\n' + + '\n' + + 'Resources\n' + + '[+] AWS::SQS::Queue Queue', + ); + }); + + test('shows the stack header and change in quiet mode', () => { + // WHEN + const formatter = new DiffFormatter({ + templateInfo: { + oldTemplate: template, + newTemplate: stackArtifact(true), + deployedTerminationProtection: false, + }, + }); + const result = formatter.formatStackDiff({ quiet: true }); + + // THEN + expect(result.numStacksWithChanges).toBe(1); + expect(stripAnsi(result.formattedDiff!)).toContain('Stack test-stack\n'); + expect(stripAnsi(result.formattedDiff!)).toContain('[~] TerminationProtection: disabled to enabled'); + }); + + test.each([ + ['unchanged', true as boolean | undefined], + ['not compared', undefined], + ])('shows nothing when termination protection is %s', (_, deployedTerminationProtection) => { + // WHEN + const formatter = new DiffFormatter({ + templateInfo: { + oldTemplate: template, + newTemplate: stackArtifact(true), + deployedTerminationProtection, + }, + }); + const result = formatter.formatStackDiff(); + + // THEN + expect(result.numStacksWithChanges).toBe(0); + expect(stripAnsi(result.formattedDiff!).trim()).toBe( + 'Stack test-stack\n' + + 'There were no differences', + ); + }); +}); + describe('formatSecurityDiff', () => { let mockNewTemplate: cxapi.CloudFormationStackArtifact; diff --git a/packages/aws-cdk/lib/cli/cdk-toolkit.ts b/packages/aws-cdk/lib/cli/cdk-toolkit.ts index 9f62e95e2..b1ca5e673 100644 --- a/packages/aws-cdk/lib/cli/cdk-toolkit.ts +++ b/packages/aws-cdk/lib/cli/cdk-toolkit.ts @@ -392,6 +392,7 @@ export class CdkToolkit { nestedStacks, mappings, environment, + deployedTerminationProtection: templateWithNestedStacks.deployedTerminationProtection, }, }); diff --git a/packages/aws-cdk/test/commands/diff.test.ts b/packages/aws-cdk/test/commands/diff.test.ts index 8bd55fb65..833f5f762 100644 --- a/packages/aws-cdk/test/commands/diff.test.ts +++ b/packages/aws-cdk/test/commands/diff.test.ts @@ -114,6 +114,50 @@ describe('fixed template', () => { }); }); +describe('termination protection', () => { + const template = { + Resources: { + Queue: { Type: 'AWS::SQS::Queue' }, + }, + }; + + beforeEach(async () => { + cloudFormation = instanceMockFrom(Deployments); + cloudFormation.readCurrentTemplateWithNestedStacks.mockResolvedValue({ + deployedRootTemplate: template, + nestedStacks: {}, + deployedTerminationProtection: false, + }); + cloudFormation.stackExists = jest.fn().mockReturnValue(Promise.resolve(true)); + cloudExecutable = await MockCloudExecutable.create({ + stacks: [{ stackName: 'A', template, terminationProtection: true }], + }, undefined, ioHost); + + toolkit = new CdkToolkit({ + cloudExecutable, + deployments: cloudFormation, + configuration: cloudExecutable.configuration, + sdkProvider: cloudExecutable.sdkProvider, + }); + }); + + test('a change in termination protection of the deployed stack is shown and counted', async () => { + // WHEN + const exitCode = await toolkit.diff({ + stackNames: ['A'], + method: 'template', + failOn: cxschema.RequireApproval.ANYCHANGE, + }); + + // THEN + expect(output()).toContain('[~] TerminationProtection: disabled to enabled'); + expect(notifySpy).toHaveBeenCalledWith(expect.objectContaining({ + message: expect.stringContaining('✨ Number of stacks with differences: 1'), + })); + expect(exitCode).toBe(1); + }); +}); + describe('import existing resources', () => { let createDiffChangeSet: jest.SpyInstance< Promise, From b8189a4f32df87ed27df8a139c3037bfd2d275fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carl=20F=C3=BCrstenberg?= Date: Thu, 26 Nov 2026 11:46:26 +0100 Subject: [PATCH 2/3] fix(toolkit-lib): report termination protection change in diff payload Before this commit, the termination protection change only appeared in the formatted text and in `numStacksWithChanges`, so a programmatic caller could see a count of changed stacks while every returned diff was empty. Add an optional `terminationProtectionChange` field to the `StackDiff` payload of CDK_TOOLKIT_I4002, and return it from `formatStackDiff()`. Also use `StackStatus.isReviewInProgress` instead of comparing the status name. Co-Authored-By: Claude Opus 5.5 --- .../cloudformation/nested-stack-helpers.ts | 2 +- .../lib/api/diff/diff-formatter.ts | 18 ++++++------- .../@aws-cdk/toolkit-lib/lib/payloads/diff.ts | 25 +++++++++++++++++++ .../toolkit-lib/lib/toolkit/toolkit.ts | 1 + .../toolkit-lib/test/actions/diff.test.ts | 5 ++++ .../toolkit-lib/test/api/diff/diff.test.ts | 3 +++ 6 files changed, 44 insertions(+), 10 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts b/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts index f2bdf8b99..7665cb956 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts @@ -48,7 +48,7 @@ export async function loadCurrentTemplateWithNestedStacks( * Whether the stack exists and is not just a placeholder for a change set that was never executed */ function hasBeenDeployed(stack: CloudFormationStack): boolean { - return stack.exists && stack.stackStatus.name !== 'REVIEW_IN_PROGRESS'; + return stack.exists && !stack.stackStatus.isReviewInProgress; } /** diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts b/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts index 23314c945..1ff4e037b 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts @@ -11,6 +11,7 @@ import { } from '@aws-cdk/cloudformation-diff'; import chalk from 'chalk'; import { PermissionChangeType } from '../../payloads'; +import type { TerminationProtectionChange } from '../../payloads'; import type { NestedStackTemplates, Template } from '../cloudformation'; import { buildLogicalToPathMap } from '../cloudformation/logical-id-map'; import { StringWriteStream } from '../streams'; @@ -49,6 +50,13 @@ interface FormatStackDiffOutput { * Complete formatted diff */ readonly formattedDiff: string; + + /** + * The change in termination protection of the root stack + * + * @default undefined - termination protection does not change, or was not compared + */ + readonly terminationProtectionChange?: TerminationProtectionChange; } /** @@ -390,7 +398,7 @@ export class DiffFormatter { formattedDiff += nextDiff.formattedDiff; } - return { numStacksWithChanges, formattedDiff }; + return { numStacksWithChanges, formattedDiff, terminationProtectionChange }; } /** @@ -560,14 +568,6 @@ function annotateMoves(templateDiff: TemplateDiff, stackName: string, mappings: }); } -/** - * A change in the termination protection of a stack - */ -interface TerminationProtectionChange { - readonly oldValue: boolean; - readonly newValue: boolean; -} - function formatTerminationProtectionChange(change: TerminationProtectionChange): string { const describe = (enabled: boolean) => enabled ? 'enabled' : 'disabled'; return [ diff --git a/packages/@aws-cdk/toolkit-lib/lib/payloads/diff.ts b/packages/@aws-cdk/toolkit-lib/lib/payloads/diff.ts index 13839b95b..811d16985 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/payloads/diff.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/payloads/diff.ts @@ -62,6 +62,21 @@ export interface DestructiveChange { readonly move?: Move; } +/** + * A change in the termination protection of a stack + */ +export interface TerminationProtectionChange { + /** + * Whether termination protection is enabled on the deployed stack + */ + readonly oldValue: boolean; + + /** + * Whether termination protection is enabled in the app + */ + readonly newValue: boolean; +} + /** * The diff formatted as different types of output */ @@ -112,6 +127,16 @@ export interface StackDiff extends SingleStack { * The changes that replace, delete or orphan an existing resource, including in nested stacks */ readonly destructiveChanges: DestructiveChange[]; + + /** + * The change in termination protection of the stack + * + * Termination protection is not part of the template, so this change is not included in `diffs`. + * It is counted in `numStacksWithChanges`. + * + * @default undefined - termination protection does not change, or was not compared + */ + readonly terminationProtectionChange?: TerminationProtectionChange; } /** diff --git a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts index 104cc7ec1..88f224d86 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts @@ -443,6 +443,7 @@ export class Toolkit extends CloudAssemblySourceBuilder { numStacksWithSecurityChanges: securityDiff.numStacksWithChanges, permissionChanges: securityDiff.permissionChangeType, destructiveChanges: findDestructiveChanges(formatter.displayedDiffs, formatter.constructPaths), + terminationProtectionChange: stackDiff.terminationProtectionChange, formattedDiff: { diff: stackDiff.formattedDiff, security: formattedSecurityDiff, diff --git a/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts b/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts index 919a5e7a8..9526afc65 100644 --- a/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts @@ -438,7 +438,12 @@ describe('diff', () => { expect(ioHost.notifySpy).toHaveBeenCalledWith(expect.objectContaining({ action: 'diff', level: 'result', + code: 'CDK_TOOLKIT_I4002', message: expect.stringContaining('TerminationProtection: enabled to disabled'), + data: expect.objectContaining({ + numStacksWithChanges: 1, + terminationProtectionChange: { oldValue: true, newValue: false }, + }), })); }); diff --git a/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts index 53f020d4f..af7b8059c 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts @@ -413,6 +413,7 @@ describe('termination protection', () => { // THEN expect(result.numStacksWithChanges).toBe(1); + expect(result.terminationProtectionChange).toEqual({ oldValue: false, newValue: true }); expect(stripAnsi(result.formattedDiff!).trim()).toBe( 'Stack test-stack\n' + 'Stack Properties\n' + @@ -433,6 +434,7 @@ describe('termination protection', () => { // THEN expect(result.numStacksWithChanges).toBe(1); + expect(result.terminationProtectionChange).toEqual({ oldValue: true, newValue: false }); expect(stripAnsi(result.formattedDiff!)).toContain('[~] TerminationProtection: enabled to disabled'); }); @@ -492,6 +494,7 @@ describe('termination protection', () => { // THEN expect(result.numStacksWithChanges).toBe(0); + expect(result.terminationProtectionChange).toBeUndefined(); expect(stripAnsi(result.formattedDiff!).trim()).toBe( 'Stack test-stack\n' + 'There were no differences', From b3ca0ad93e7f99b5939a75dbdc48c782aa23f82a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carl=20F=C3=BCrstenberg?= Date: Mon, 30 Nov 2026 17:07:13 +0100 Subject: [PATCH 3/3] refactor(toolkit-lib): group deployed stack properties and use IDifference Read the deployed termination protection into a `CloudFormationStackProperties` structure, so other stack properties can be added next to it later. Use the existing `IDifference` from cloudformation-diff for the termination protection change instead of a dedicated type. Co-Authored-By: Claude Opus 5.5 --- .../lib/actions/diff/private/helpers.ts | 2 +- .../cloudformation/nested-stack-helpers.ts | 18 ++++++++++--- .../lib/api/diff/diff-formatter.ts | 27 ++++++++++--------- .../@aws-cdk/toolkit-lib/lib/payloads/diff.ts | 19 ++----------- .../toolkit-lib/test/actions/diff.test.ts | 4 +-- .../cloudformation-deployments.test.ts | 4 +-- .../toolkit-lib/test/api/diff/diff.test.ts | 16 +++++------ packages/aws-cdk/lib/cli/cdk-toolkit.ts | 2 +- packages/aws-cdk/test/commands/diff.test.ts | 2 +- 9 files changed, 45 insertions(+), 49 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/actions/diff/private/helpers.ts b/packages/@aws-cdk/toolkit-lib/lib/actions/diff/private/helpers.ts index 5a0261219..d4954b0fe 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/actions/diff/private/helpers.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/actions/diff/private/helpers.ts @@ -122,7 +122,7 @@ async function cfnDiff( changeSet, mappings, environment, - deployedTerminationProtection: templateWithNestedStacks.deployedTerminationProtection, + deployedStackProperties: templateWithNestedStacks.deployedStackProperties, }); } diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts b/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts index 7665cb956..c0499e9c4 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts @@ -14,11 +14,21 @@ export interface RootTemplateWithNestedStacks { }; /** - * Whether termination protection is enabled on the deployed root stack + * Properties of the deployed root stack that are not part of its template * - * @default undefined - the stack does not exist, or the setting was not read + * @default undefined - the stack does not exist, or the properties were not read */ - readonly deployedTerminationProtection?: boolean; + readonly deployedStackProperties?: CloudFormationStackProperties; +} + +/** + * Properties of a deployed CloudFormation stack that are not part of its template + */ +export interface CloudFormationStackProperties { + /** + * Whether termination protection is enabled on the stack + */ + readonly terminationProtection: boolean; } /** @@ -40,7 +50,7 @@ export async function loadCurrentTemplateWithNestedStacks( return { deployedRootTemplate, nestedStacks, - deployedTerminationProtection: hasBeenDeployed(rootStack) ? !!rootStack.terminationProtection : undefined, + deployedStackProperties: hasBeenDeployed(rootStack) ? { terminationProtection: !!rootStack.terminationProtection } : undefined, }; } diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts b/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts index 1ff4e037b..558148dd3 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts @@ -1,18 +1,19 @@ import { format } from 'node:util'; import * as cxapi from '@aws-cdk/cloud-assembly-api'; import { + Difference, formatDifferences, formatSecurityChanges, fullDiff, mangleLikeCloudFormation, type DescribeChangeSetOutput, + type IDifference, type ResourceDifference, type TemplateDiff, } from '@aws-cdk/cloudformation-diff'; import chalk from 'chalk'; import { PermissionChangeType } from '../../payloads'; -import type { TerminationProtectionChange } from '../../payloads'; -import type { NestedStackTemplates, Template } from '../cloudformation'; +import type { CloudFormationStackProperties, NestedStackTemplates, Template } from '../cloudformation'; import { buildLogicalToPathMap } from '../cloudformation/logical-id-map'; import { StringWriteStream } from '../streams'; @@ -56,7 +57,7 @@ interface FormatStackDiffOutput { * * @default undefined - termination protection does not change, or was not compared */ - readonly terminationProtectionChange?: TerminationProtectionChange; + readonly terminationProtectionChange?: IDifference; } /** @@ -168,14 +169,14 @@ export interface TemplateInfo { readonly environment?: cxapi.Environment; /** - * Whether termination protection is enabled on the deployed stack. + * Properties of the deployed stack that are not part of its template. * - * If this differs from the termination protection of `newTemplate`, the change is shown as a stack property change. + * Any that differ from the properties of `newTemplate` are shown as stack property changes. * Only set this when comparing against a deployed stack. * - * @default undefined - termination protection is not compared + * @default undefined - stack properties are not compared */ - readonly deployedTerminationProtection?: boolean; + readonly deployedStackProperties?: CloudFormationStackProperties; } /** @@ -295,13 +296,13 @@ export class DiffFormatter { /** * The change in termination protection of the root stack, if there is one */ - private terminationProtectionChange(): TerminationProtectionChange | undefined { - const oldValue = this.templateInfo.deployedTerminationProtection; + private terminationProtectionChange(): IDifference | undefined { + const oldValue = this.templateInfo.deployedStackProperties?.terminationProtection; const newValue = this.templateInfo.newTemplate.terminationProtection ?? false; if (oldValue === undefined || oldValue === newValue) { return undefined; } - return { oldValue, newValue }; + return new Difference(oldValue, newValue); } private formatStackDiffHelper(params: { @@ -315,7 +316,7 @@ export class DiffFormatter { // Only set for the root stack; nested stacks share their parent's environment. environmentString?: string; // Only set for the root stack; termination protection is a property of the root stack. - terminationProtectionChange?: TerminationProtectionChange; + terminationProtectionChange?: IDifference; }, options: ReusableStackDiffOptions = {}): FormatStackDiffOutput { const { oldTemplate, newTemplate, stackName, nestedStacks, changeSet, mappings, logicalIdMap, environmentString, terminationProtectionChange, @@ -568,8 +569,8 @@ function annotateMoves(templateDiff: TemplateDiff, stackName: string, mappings: }); } -function formatTerminationProtectionChange(change: TerminationProtectionChange): string { - const describe = (enabled: boolean) => enabled ? 'enabled' : 'disabled'; +function formatTerminationProtectionChange(change: IDifference): string { + const describe = (enabled?: boolean) => enabled ? 'enabled' : 'disabled'; return [ chalk.underline(chalk.bold('Stack Properties')), `${chalk.yellow('[~]')} TerminationProtection: ${describe(change.oldValue)} to ${describe(change.newValue)}`, diff --git a/packages/@aws-cdk/toolkit-lib/lib/payloads/diff.ts b/packages/@aws-cdk/toolkit-lib/lib/payloads/diff.ts index 811d16985..7391600f4 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/payloads/diff.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/payloads/diff.ts @@ -1,4 +1,4 @@ -import type { ITemplateDiff, Move, ResourceImpact } from '@aws-cdk/cloudformation-diff'; +import type { IDifference, ITemplateDiff, Move, ResourceImpact } from '@aws-cdk/cloudformation-diff'; import type { Duration, SingleStack } from './types'; /** @@ -62,21 +62,6 @@ export interface DestructiveChange { readonly move?: Move; } -/** - * A change in the termination protection of a stack - */ -export interface TerminationProtectionChange { - /** - * Whether termination protection is enabled on the deployed stack - */ - readonly oldValue: boolean; - - /** - * Whether termination protection is enabled in the app - */ - readonly newValue: boolean; -} - /** * The diff formatted as different types of output */ @@ -136,7 +121,7 @@ export interface StackDiff extends SingleStack { * * @default undefined - termination protection does not change, or was not compared */ - readonly terminationProtectionChange?: TerminationProtectionChange; + readonly terminationProtectionChange?: IDifference; } /** diff --git a/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts b/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts index 9526afc65..7b5955747 100644 --- a/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts @@ -424,7 +424,7 @@ describe('diff', () => { jest.spyOn(deployments.Deployments.prototype, 'readCurrentTemplateWithNestedStacks').mockResolvedValue({ deployedRootTemplate: {}, nestedStacks: {}, - deployedTerminationProtection: true, + deployedStackProperties: { terminationProtection: true }, }); // WHEN @@ -442,7 +442,7 @@ describe('diff', () => { message: expect.stringContaining('TerminationProtection: enabled to disabled'), data: expect.objectContaining({ numStacksWithChanges: 1, - terminationProtectionChange: { oldValue: true, newValue: false }, + terminationProtectionChange: expect.objectContaining({ oldValue: true, newValue: false }), }), })); }); diff --git a/packages/@aws-cdk/toolkit-lib/test/api/deployments/cloudformation-deployments.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/deployments/cloudformation-deployments.test.ts index 2e46e776b..561ccdba8 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/deployments/cloudformation-deployments.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/deployments/cloudformation-deployments.test.ts @@ -424,7 +424,7 @@ test.each([ const result = await deployments.readCurrentTemplateWithNestedStacks(testStack({ stackName: 'boop' })); // THEN - expect(result.deployedTerminationProtection).toBe(expected); + expect(result.deployedStackProperties).toEqual({ terminationProtection: expected }); }); test.each([ @@ -438,7 +438,7 @@ test.each([ const result = await deployments.readCurrentTemplateWithNestedStacks(testStack({ stackName: 'boop' })); // THEN - expect(result.deployedTerminationProtection).toBeUndefined(); + expect(result.deployedStackProperties).toBeUndefined(); }); test('readCurrentTemplateWithNestedStacks() can handle non-Resources in the template', async () => { diff --git a/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts index af7b8059c..1099f0538 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts @@ -406,14 +406,14 @@ describe('termination protection', () => { templateInfo: { oldTemplate: template, newTemplate: stackArtifact(true), - deployedTerminationProtection: false, + deployedStackProperties: { terminationProtection: false }, }, }); const result = formatter.formatStackDiff(); // THEN expect(result.numStacksWithChanges).toBe(1); - expect(result.terminationProtectionChange).toEqual({ oldValue: false, newValue: true }); + expect(result.terminationProtectionChange).toMatchObject({ oldValue: false, newValue: true, isUpdate: true }); expect(stripAnsi(result.formattedDiff!).trim()).toBe( 'Stack test-stack\n' + 'Stack Properties\n' + @@ -427,14 +427,14 @@ describe('termination protection', () => { templateInfo: { oldTemplate: template, newTemplate: stackArtifact(undefined), - deployedTerminationProtection: true, + deployedStackProperties: { terminationProtection: true }, }, }); const result = formatter.formatStackDiff(); // THEN expect(result.numStacksWithChanges).toBe(1); - expect(result.terminationProtectionChange).toEqual({ oldValue: true, newValue: false }); + expect(result.terminationProtectionChange).toMatchObject({ oldValue: true, newValue: false, isUpdate: true }); expect(stripAnsi(result.formattedDiff!)).toContain('[~] TerminationProtection: enabled to disabled'); }); @@ -444,7 +444,7 @@ describe('termination protection', () => { templateInfo: { oldTemplate: {}, newTemplate: stackArtifact(true), - deployedTerminationProtection: false, + deployedStackProperties: { terminationProtection: false }, }, }); const result = formatter.formatStackDiff(); @@ -467,7 +467,7 @@ describe('termination protection', () => { templateInfo: { oldTemplate: template, newTemplate: stackArtifact(true), - deployedTerminationProtection: false, + deployedStackProperties: { terminationProtection: false }, }, }); const result = formatter.formatStackDiff({ quiet: true }); @@ -481,13 +481,13 @@ describe('termination protection', () => { test.each([ ['unchanged', true as boolean | undefined], ['not compared', undefined], - ])('shows nothing when termination protection is %s', (_, deployedTerminationProtection) => { + ])('shows nothing when termination protection is %s', (_, terminationProtection) => { // WHEN const formatter = new DiffFormatter({ templateInfo: { oldTemplate: template, newTemplate: stackArtifact(true), - deployedTerminationProtection, + deployedStackProperties: terminationProtection === undefined ? undefined : { terminationProtection }, }, }); const result = formatter.formatStackDiff(); diff --git a/packages/aws-cdk/lib/cli/cdk-toolkit.ts b/packages/aws-cdk/lib/cli/cdk-toolkit.ts index b1ca5e673..a61b7cce2 100644 --- a/packages/aws-cdk/lib/cli/cdk-toolkit.ts +++ b/packages/aws-cdk/lib/cli/cdk-toolkit.ts @@ -392,7 +392,7 @@ export class CdkToolkit { nestedStacks, mappings, environment, - deployedTerminationProtection: templateWithNestedStacks.deployedTerminationProtection, + deployedStackProperties: templateWithNestedStacks.deployedStackProperties, }, }); diff --git a/packages/aws-cdk/test/commands/diff.test.ts b/packages/aws-cdk/test/commands/diff.test.ts index 833f5f762..741e760ef 100644 --- a/packages/aws-cdk/test/commands/diff.test.ts +++ b/packages/aws-cdk/test/commands/diff.test.ts @@ -126,7 +126,7 @@ describe('termination protection', () => { cloudFormation.readCurrentTemplateWithNestedStacks.mockResolvedValue({ deployedRootTemplate: template, nestedStacks: {}, - deployedTerminationProtection: false, + deployedStackProperties: { terminationProtection: false }, }); cloudFormation.stackExists = jest.fn().mockReturnValue(Promise.resolve(true)); cloudExecutable = await MockCloudExecutable.create({