Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ async function cfnDiff(
changeSet,
mappings,
environment,
deployedStackProperties: templateWithNestedStacks.deployedStackProperties,
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,23 @@ export interface RootTemplateWithNestedStacks {
readonly nestedStacks: {
[nestedStackLogicalId: string]: NestedStackTemplates;
};

/**
* Properties of the deployed root stack that are not part of its template
*
* @default undefined - the stack does not exist, or the properties were not read
*/
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;
}

/**
Expand All @@ -22,7 +39,8 @@ export async function loadCurrentTemplateWithNestedStacks(
sdk: SDK,
retrieveProcessedTemplate: boolean = false,
): Promise<RootTemplateWithNestedStacks> {
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,
Expand All @@ -32,9 +50,17 @@ export async function loadCurrentTemplateWithNestedStacks(
return {
deployedRootTemplate,
nestedStacks,
deployedStackProperties: hasBeenDeployed(rootStack) ? { terminationProtection: !!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.isReviewInProgress;
}

/**
* Returns the currently deployed template from CloudFormation that corresponds to `stackArtifact`.
*/
Expand Down
64 changes: 58 additions & 6 deletions packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts
Original file line number Diff line number Diff line change
@@ -1,17 +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 { NestedStackTemplates, Template } from '../cloudformation';
import type { CloudFormationStackProperties, NestedStackTemplates, Template } from '../cloudformation';
import { buildLogicalToPathMap } from '../cloudformation/logical-id-map';
import { StringWriteStream } from '../streams';

Expand Down Expand Up @@ -49,6 +51,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?: IDifference<boolean>;
}

/**
Expand Down Expand Up @@ -158,6 +167,16 @@ export interface TemplateInfo {
* @default undefined - no environment is shown
*/
readonly environment?: cxapi.Environment;

/**
* Properties of the deployed stack that are not part of its template.
*
* 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 - stack properties are not compared
*/
readonly deployedStackProperties?: CloudFormationStackProperties;
}

/**
Expand Down Expand Up @@ -270,9 +289,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(): IDifference<boolean> | undefined {
const oldValue = this.templateInfo.deployedStackProperties?.terminationProtection;
const newValue = this.templateInfo.newTemplate.terminationProtection ?? false;
if (oldValue === undefined || oldValue === newValue) {
return undefined;
}
return new Difference(oldValue, newValue);
}

private formatStackDiffHelper(params: {
oldTemplate: Template;
newTemplate: Template;
Expand All @@ -283,8 +315,12 @@ export class DiffFormatter {
logicalIdMap: Record<string, string>;
// 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?: IDifference<boolean>;
}, 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);
Expand All @@ -296,7 +332,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`));
}

Expand Down Expand Up @@ -325,11 +361,17 @@ export class DiffFormatter {
}
const metadataWasFiltered = diffWasNonEmpty && activeDiff.isEmpty;

if (!activeDiff.isEmpty) {
if (terminationProtectionChange) {
stream.write(formatTerminationProtectionChange(terminationProtectionChange));
}

if (!activeDiff.isEmpty || terminationProtectionChange) {
numStacksWithChanges++;
}
Comment thread
azatoth marked this conversation as resolved.
Resolved

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`);
}
Expand Down Expand Up @@ -357,7 +399,7 @@ export class DiffFormatter {
formattedDiff += nextDiff.formattedDiff;
}

return { numStacksWithChanges, formattedDiff };
return { numStacksWithChanges, formattedDiff, terminationProtectionChange };
}

/**
Expand Down Expand Up @@ -526,3 +568,13 @@ function annotateMoves(templateDiff: TemplateDiff, stackName: string, mappings:
}
});
}

function formatTerminationProtectionChange(change: IDifference<boolean>): 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');
}
12 changes: 11 additions & 1 deletion packages/@aws-cdk/toolkit-lib/lib/payloads/diff.ts
Original file line number Diff line number Diff line change
@@ -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';

/**
Expand Down Expand Up @@ -112,6 +112,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?: IDifference<boolean>;
}

/**
Expand Down
1 change: 1 addition & 0 deletions packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
28 changes: 28 additions & 0 deletions packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,34 @@ describe('diff', () => {
}));
});

test('shows a change in termination protection of the deployed stack', async () => {
// GIVEN
jest.spyOn(deployments.Deployments.prototype, 'readCurrentTemplateWithNestedStacks').mockResolvedValue({
deployedRootTemplate: {},
nestedStacks: {},
deployedStackProperties: { terminationProtection: 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',
code: 'CDK_TOOLKIT_I4002',
message: expect.stringContaining('TerminationProtection: enabled to disabled'),
data: expect.objectContaining({
numStacksWithChanges: 1,
terminationProtectionChange: expect.objectContaining({ oldValue: true, newValue: false }),
}),
}));
});

describe('DiffMethod.ChangeSet', () => {
test('ChangeSet diff method falls back to template only if changeset not found', async () => {
// WHEN
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
DescribeStackEventsCommand,
type DescribeStackEventsCommandInput,
DescribeStacksCommand,
GetTemplateCommand,
ListStackResourcesCommand,
RollbackStackCommand,
type StackResourceSummary,
Expand Down Expand Up @@ -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.deployedStackProperties).toEqual({ terminationProtection: 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.deployedStackProperties).toBeUndefined();
});

test('readCurrentTemplateWithNestedStacks() can handle non-Resources in the template', async () => {
const stackSummary = stackSummaryOf(
'NestedStack',
Expand Down
Loading
Loading