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 @@ -1207,6 +1207,10 @@ switch (stackSet) {
case 'stage-with-no-stacks':
break;

case 'stage-only':
new SomeStage(app, `${stackPrefix}-stage`);
break;

default:
throw new Error(`Unrecognized INTEG_STACK_SET: '${stackSet}'`);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { integTest, withDefaultFixture } from '../../../lib';

integTest('cdk destroy does not fail even if the stacks do not exist', withDefaultFixture(async (fixture) => {
const nonExistingStackName1 = 'non-existing-stack-1';
const nonExistingStackName2 = 'non-existing-stack-2';

await expect(fixture.cdkDestroy([nonExistingStackName1, nonExistingStackName2])).resolves.not.toThrow();
}));

integTest('cdk destroy with no force option exits without prompt if the stacks do not exist', withDefaultFixture(async (fixture) => {
const nonExistingStackName1 = 'non-existing-stack-1';
const nonExistingStackName2 = 'non-existing-stack-2';

await expect(fixture.cdkDestroy([nonExistingStackName1, nonExistingStackName2], {
force: false,
})).resolves.not.toThrow();
}));

integTest('cdk destroy does not fail even if the stages do not exist', withDefaultFixture(async (fixture) => {
await expect(fixture.cdkDestroy('NonExistent/*')).resolves.not.toThrow();
}));
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { DescribeStacksCommand } from '@aws-sdk/client-cloudformation';
import { integTest, withDefaultFixture } from '../../../lib';

integTest('cdk destroy can destroy stacks in stage-only configuration', withDefaultFixture(async (fixture) => {
const integStackSet = 'stage-only';

const stageNameSuffix = 'stage';
const specifiedStackName = `${stageNameSuffix}/*`;

await fixture.cdkDeploy(specifiedStackName, {
modEnv: {
INTEG_STACK_SET: integStackSet,
},
});

const stackName = `${fixture.fullStackName(stageNameSuffix)}-StackInStage`;
const stack = await fixture.aws.cloudFormation.send(new DescribeStacksCommand({ StackName: stackName }));
expect(stack.Stacks?.length ?? 0).toEqual(1);

await fixture.cdkDestroy(specifiedStackName, {
modEnv: {
INTEG_STACK_SET: integStackSet,
},
});

await expect(fixture.aws.cloudFormation.send(new DescribeStacksCommand({ StackName: stackName })))
.rejects.toThrow(/does not exist/);
}));
2 changes: 2 additions & 0 deletions packages/@aws-cdk/toolkit-lib/docs/message-registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ Please let us know by [opening an issue](https://github.com/aws/aws-cdk-cli/issu
| `CDK_TOOLKIT_I7010` | Confirm destroy stacks | `info` | {@link ConfirmationRequest} |
| `CDK_TOOLKIT_I7100` | Stack destroy progress | `info` | {@link StackDestroyProgress} |
| `CDK_TOOLKIT_I7101` | Start stack destroying | `trace` | {@link StackDestroy} |
| `CDK_TOOLKIT_W7010` | A provided stack name does not match any stack | `warn` | n/a |
| `CDK_TOOLKIT_W7011` | No stacks match the provided names, nothing to destroy | `warn` | n/a |
| `CDK_TOOLKIT_I7900` | Stack deletion succeeded | `result` | [cxapi.CloudFormationStackArtifact](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_cx-api.CloudFormationStackArtifact.html) |
| `CDK_TOOLKIT_W7902` | Express Mode deletion completed with resources still tearing down | `warn` | n/a |
| `CDK_TOOLKIT_E7010` | Action was aborted due to negative confirmation of request | `error` | n/a |
Expand Down
9 changes: 9 additions & 0 deletions packages/@aws-cdk/toolkit-lib/lib/api/io/private/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,15 @@ export const IO = {
interface: 'StackDestroy',
}),

CDK_TOOLKIT_W7010: make.warn({
code: 'CDK_TOOLKIT_W7010',
description: 'A provided stack name does not match any stack',
}),
CDK_TOOLKIT_W7011: make.warn({
code: 'CDK_TOOLKIT_W7011',
description: 'No stacks match the provided names, nothing to destroy',
}),
Comment on lines +401 to +408

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Like said elsewhere, I think a single message will be enough but it should carry a payload of the unmatched selector and idenfified matches.


CDK_TOOLKIT_I7900: make.result<cxapi.CloudFormationStackArtifact>({
code: 'CDK_TOOLKIT_I7900',
description: 'Stack deletion succeeded',
Expand Down
45 changes: 44 additions & 1 deletion packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ function isFileEvent(event: EventName): event is FileEvent {
return (FILE_EVENTS as readonly string[]).includes(event);
}
import * as fs from 'fs-extra';
import * as picomatch from 'picomatch';
import { NonInteractiveIoHost } from './non-interactive-io-host';
import type { ToolkitServices } from './private';
import { assemblyFromSource } from './private';
Expand Down Expand Up @@ -1621,12 +1622,21 @@ export class Toolkit extends CloudAssemblySourceBuilder {
const ioHelper = asIoHelper(this.ioHost, action);
const stacks = await assembly.selectStacksV2(selectStacks);

await this.suggestStacks(ioHelper, assembly, selectStacks, stacks);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should only call this if the original selector returned 0 results.


const ret: DestroyResult = {
stacks: [],
};

if (stacks.stackCount === 0) {
await ioHelper.notify(IO.CDK_TOOLKIT_W7011.msg(

@mrgrain mrgrain Jul 7, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think both messages can be folded into a single message that informs the user that no matching stacks were found. And if we have identified possible close matches ("candidates"), then we suggest them ("Did you mean...").

The Toolkit message should include a payload of the unmatched pattern and the identified matches as string[] | undefined.

`No stacks match the name(s): ${chalk.red((selectStacks.patterns ?? []).join(', '))}`,
));
return ret;
}

const motivation = 'Destroying stacks is an irreversible action';
const question = `Are you sure you want to delete: ${chalk.red(stacks.hierarchicalIds.join(', '))}`;
const question = `Are you sure you want to delete: ${chalk.blue(stacks.hierarchicalIds.join(', '))}`;
const confirmed = await ioHelper.requestResponse(IO.CDK_TOOLKIT_I7010.req(question, { motivation }));
if (!confirmed) {
await ioHelper.notify(IO.CDK_TOOLKIT_E7010.msg('Aborted by user'));
Expand Down Expand Up @@ -1694,6 +1704,39 @@ export class Toolkit extends CloudAssemblySourceBuilder {
}
}

/**
* Warn about destroy patterns that matched no stack, suggesting a close match
* when one exists (e.g. only the casing differs). Stacks nested inside a stage
* are considered, so a staged stack can be suggested too.
*/
private async suggestStacks(
ioHelper: IoHelper,
assembly: StackAssembly,
selector: StackSelector,
selected: StackCollection,
): Promise<void> {
const patterns = selector.patterns ?? [];
if (patterns.length === 0) {
return;
}

const allStacks = await assembly.selectStacksV2(ALL_STACKS);

for (const pattern of patterns) {
const matched = selected.stackArtifacts.some((stack) => picomatch.isMatch(stack.hierarchicalId, pattern));
if (matched) {
continue;
}
Comment on lines +1726 to +1729

@mrgrain mrgrain Jul 7, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you explain what purpose this is serving? I just don't understand it. We are excluding any of the stacks that already match the pattern themselves? But why?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This handles the case where several names are given and only some exist. E.g. cdk destroy StackA Typo: StackA is destroyed, Typo matches nothing. The matched check skips StackA and warns only about Typo ("Did you mean …?").

With "only warn when 0 stacks matched", a typo mixed in with valid names would slip through unnoticed, that's what I wanted to catch. That said, if you'd prefer a single message (only when nothing matched at all), I'm happy to fold it into one payload-carrying message. Which do you prefer?

@mrgrain mrgrain Jul 7, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, thank you. I understand now what this is trying to achieve. Let me think about this for a bit. Some of my comments are now obviously contingent on this decision here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Holding off until the direction above is settled, then I'll adjust accordingly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mrgrain How has it been since then?


const closeMatches = allStacks.stackArtifacts
.filter((stack) => picomatch.isMatch(stack.hierarchicalId.toLowerCase(), pattern.toLowerCase()))
.map((stack) => stack.hierarchicalId);
Comment on lines +1712 to +1733

@mrgrain mrgrain Jul 7, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function to match candidates (basically to this line) should live on StackAssembly class. It should not log any output but return a string[].


const suggestion = closeMatches.length > 0 ? ` Do you mean ${chalk.blue(closeMatches.join(', '))}?` : '';
await ioHelper.notify(IO.CDK_TOOLKIT_W7010.msg(`${chalk.red(pattern)} does not exist.${suggestion}`));
}
}

/**
* Create a deployments class
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import * as core from 'aws-cdk-lib/core';

/**
* An app with a top-level stack plus a stack nested inside a Stage.
*
* Hierarchical ids: `TopLevelStack` and `Stage/StackInStage`. Used to exercise
* destroy/suggestion behavior across both top-level and nested-stage stacks.
*/
export default async () => {
const app = new core.App({ autoSynth: false });
new core.Stack(app, 'TopLevelStack');
const stage = new core.Stage(app, 'Stage');
new core.Stack(stage, 'StackInStage');

return app.synth();
};
16 changes: 16 additions & 0 deletions packages/@aws-cdk/toolkit-lib/test/_fixtures/stage-only/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import * as core from 'aws-cdk-lib/core';

/**
* An app whose only stack lives inside a Stage (no top-level stacks).
*
* This is the configuration that regressed the original `cdk destroy` warning
* feature: code that only looked at top-level stacks could not see (or suggest)
* stacks nested in a Stage. The stack's hierarchical id is `Stage/StackInStage`.
*/
export default async () => {
const app = new core.App({ autoSynth: false });
const stage = new core.Stage(app, 'Stage');
new core.Stack(stage, 'StackInStage');

return app.synth();
};
Loading
Loading