diff --git a/packages/aws-cdk/lib/commands/migrate.ts b/packages/aws-cdk/lib/commands/migrate.ts index de1fe4f38..49d0090b6 100644 --- a/packages/aws-cdk/lib/commands/migrate.ts +++ b/packages/aws-cdk/lib/commands/migrate.ts @@ -856,9 +856,21 @@ export class CfnTemplateGeneratorProvider { } resourceList = deduplicateResources(resourceList); - return process.env.MIGRATE_INTEG_TEST - ? resourceIdentifiers(resourceList) - : resourceIdentifiers(excludeManaged(resourceList)); + if (process.env.MIGRATE_INTEG_TEST) { + return resourceIdentifiers(resourceList); + } + + const unmanagedResources = excludeManaged(resourceList); + if (unmanagedResources.length === 0) { + const matching = filters.length > 0 + ? `All ${resourceList.length} resources matching filters ${filters.join(' ')}` + : `All ${resourceList.length} scanned resources`; + throw new ToolkitError( + 'NoUnmanagedResourcesFound', + `${matching} are already managed by a CloudFormation stack. Use --from-stack to migrate an existing stack.`, + ); + } + return resourceIdentifiers(unmanagedResources); } /** diff --git a/packages/aws-cdk/test/commands/migrate.test.ts b/packages/aws-cdk/test/commands/migrate.test.ts index bd04e82c8..2e03314df 100644 --- a/packages/aws-cdk/test/commands/migrate.test.ts +++ b/packages/aws-cdk/test/commands/migrate.test.ts @@ -507,7 +507,7 @@ describe('generateTemplate', () => { }) .on(ListResourceScanResourcesCommand) .resolves({ - Resources: [sampleResource2], + Resources: [{ ...sampleResource2, ManagedByStack: false }], }) .on(CreateGeneratedTemplateCommand) .resolves({ @@ -681,6 +681,28 @@ describe('generateTemplate', () => { ); }); + test('generateTemplate throws a clear error when every resource matching the filters is already managed by a stack', async () => { + mockCloudFormationClient + .on(ListResourceScanResourcesCommand) + .resolves({ + Resources: [sampleResource, sampleResource2], + }); + + const opts: GenerateTemplateOptions = { + ioHelper, + stackName: stackName, + filters: ['tag-key=user:Application,tag-value=my-app'], + fromScan: FromScan.MOST_RECENT, + sdkProvider: sdkProvider, + environment: environment, + }; + + await expect(generateTemplate(opts)).rejects.toThrow( + 'All 2 resources matching filters tag-key=user:Application,tag-value=my-app are already managed by a CloudFormation stack. Use --from-stack to migrate an existing stack.', + ); + expect(mockCloudFormationClient).not.toHaveReceivedCommand(CreateGeneratedTemplateCommand); + }); + test('generateTemplate shows the progress of a scan and a template when the output is not a terminal', async () => { // GIVEN a scan and a template that are still in progress mockCloudFormationClient