Skip to content

Commit

Permalink
feat(migrate): Add CDK Migrate --from-scan functionality (#28962)
Browse files Browse the repository at this point in the history
### `cdk migrate`

⚠️**CAUTION**⚠️: CDK Migrate is currently experimental and may have breaking changes in the future. 

CDK Migrate generates a CDK app from deployed AWS resources using `--from-scan`, deployed AWS CloudFormation stacks using `--from-stack`, and local AWS CloudFormation templates using `--from-path`. 

To learn more about the CDK Migrate feature, see [Migrate to AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/migrate.html). For more information on `cdk migrate` command options, see [cdk migrate command reference](https://docs.aws.amazon.com/cdk/v2/guide/ref-cli-cdk-migrate.html).

The new CDK app will be initialized in the current working directory and will include a single stack that is named with the value you provide using `--stack-name`. The new stack, app, and directory will all use this name. To specify a different output directory, use `--output-path`. You can create the new CDK app in any CDK supported programming language using `--language`.

#### Migrate from an AWS CloudFormation stack

Migrate from a deployed AWS CloudFormation stack in a specific AWS account and AWS Region using `--from-stack`. Provide `--stack-name` to identify the name of your stack. Account and Region information are retrieved from default CDK CLI sources. Use `--account` and `--region` options to provide other values. The following is an example that migrates **myCloudFormationStack** to a new CDK app using TypeScript:

```console
$ cdk migrate --language typescript --from-stack --stack-name 'myCloudFormationStack'
```

#### Migrate from a local AWS CloudFormation template

Migrate from a local `YAML` or `JSON` AWS CloudFormation template using `--from-path`. Provide a name for the stack that will be created in your new CDK app using `--stack-name`. Account and Region information are retrieved from default CDK CLI sources. Use `--account` and `--region` options to provide other values. The following is an example that creates a new CDK app using TypeScript that includes a **myCloudFormationStack** stack from a local `template.json` file:

```console
$ cdk migrate --language typescript --from-path "./template.json" --stack-name "myCloudFormationStack"
```

#### Migrate from deployed AWS resources

Migrate from deployed AWS resources in a specific AWS account and Region that are not associated with an AWS CloudFormation stack using `--from-scan`. These would be resources that were provisioned outside of an IaC tool. CDK Migrate utilizes the IaC generator service to scan for resources and generate a template. Then, the CDK CLI references the template to create a new CDK app. To learn more about IaC generator, see [Generating templates for existing resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC.html).

Account and Region information are retrieved from default CDK CLI sources. Use `--account` and `--region` options to provide other values. The following is an example that creates a new CDK app using TypeScript that includes a new **myCloudFormationStack** stack from deployed resources:

```console
$ cdk migrate --language typescript --from-scan --stack-name "myCloudFormationStack"
```

Since CDK Migrate relies on the IaC generator service, any limitations of IaC generator will apply to CDK Migrate. For general limitations, see [Considerations](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC.html#generate-template-considerations). 

IaC generator limitations with discovering resource and property values will also apply here. As a result, CDK Migrate will only migrate resources supported by IaC generator. Some of your resources may not be supported and some property values may not be accessible. For more information, see [Iac generator and write-only properties](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC-write-only-properties.html) and [Supported resource types](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC-supported-resources.html).

You can specify filters using `--filter` to specify which resources to migrate. This is a good option to use if you are over the IaC generator total resource limit.

After migration, you must resolve any write-only properties that were detected by IaC generator from your deployed resources. To learn more, see [Resolve write-only properties](https://docs.aws.amazon.com/cdk/v2/guide/migrate.html#migrate-resources-writeonly).

#### Examples

##### Generate a TypeScript CDK app from a local AWS CloudFormation template.json file

```console
$ # template.json is a valid cloudformation template in the local directory
$ cdk migrate --stack-name MyAwesomeApplication --language typescript --from-path MyTemplate.json
```

This command generates a new directory named `MyAwesomeApplication` within your current working directory, and  
then initializes a new CDK application within that directory. The CDK app contains a `MyAwesomeApplication` stack with resources configured to match those in your local CloudFormation template. 

This results in a CDK application with the following structure, where the lib directory contains a stack definition
with the same resource configuration as the provided template.json.

```console
├── README.md
├── bin
│   └── my_awesome_application.ts
├── cdk.json
├── jest.config.js
├── lib
│   └── my_awesome_application-stack.ts
├── package.json
├── tsconfig.json
```

##### Generate a Python CDK app from a deployed stack

If you already have a CloudFormation stack deployed in your account and would like to manage it with CDK, you can migrate the deployed stack to a new CDK app. The value provided with `--stack-name` must match the name of the deployed stack.

```console
$ # generate a Python application from MyDeployedStack in your account
$ cdk migrate --stack-name MyDeployedStack --language python --from-stack
```

This will generate a Python CDK app which will synthesize the same configuration of resources as the deployed stack.

##### Generate a TypeScript CDK app from deployed AWS resources that are not associated with a stack

If you have resources in your account that were provisioned outside AWS IaC tools and would like to manage them with the CDK, you can use the `--from-scan` option to generate the application. 

In this example, we use the `--filter` option to specify which resources to migrate.  You can filter resources to limit the number of resources migrated to only those specified by the `--filter` option, including any resources they depend on, or resources that depend on them (for example A filter which specifies a single Lambda Function, will find that specific table and any alarms that may monitor it). The `--filter` argument offers both AND as well as OR filtering.

OR filtering can be specified by passing multiple `--filter` options, and AND filtering can be specified by passing a single `--filter` option with multiple comma separated key/value pairs as seen below (see below for examples). It is recommended to use the `--filter` option to limit the number of resources returned as some resource types provide sample resources by default in all accounts which can add to the resource limits.

`--from-scan` takes 3 potential arguments: `--new`, `most-recent`, and undefined. If `--new` is passed, CDK Migrate will initiate a new scan of the account and use that new scan to discover resources. If `--most-recent` is passed, CDK Migrate will use the most recent scan of the account to discover resources. If neither `--new` nor `--most-recent` are passed, CDK Migrate will take the most recent scan of the account to discover resources, unless there is no recent scan, in which case it will initiate a new scan. 

```
# Filtering options
identifier|id|resource-identifier=<resource-specific-resource-identifier-value>
type|resource-type-prefix=<resource-type-prefix>
tag-key=<tag-key>
tag-value=<tag-value>
```

##### Additional examples of migrating from deployed resources

```console
$ # Generate a typescript application from all un-managed resources in your account
$ cdk migrate --stack-name MyAwesomeApplication --language typescript --from-scan

$ # Generate a typescript application from all un-managed resources in your account with the tag key "Environment" AND the tag value "Production"
$ cdk migrate --stack-name MyAwesomeApplication --language typescript --from-scan --filter tag-key=Environment,tag-value=Production

$ # Generate a python application from any dynamoDB resources with the tag-key "dev" AND the tag-value "true" OR any SQS::Queue
$ cdk migrate --stack-name MyAwesomeApplication --language python --from-scan --filter type=AWS::DynamoDb::,tag-key=dev,tag-value=true --filter type=SQS::Queue

$ # Generate a typescript application from a specific lambda function by providing it's specific resource identifier
$ cdk migrate --stack-name MyAwesomeApplication --language typescript --from-scan --filter identifier=myAwesomeLambdaFunction
```

#### **CDK Migrate Limitations**

- CDK Migrate does not currently support nested stacks, custom resources, or the `Fn::ForEach` intrinsic function.

- CDK Migrate will only generate L1 constructs and does not currently support any higher level abstractions.

- CDK Migrate successfully generating an application does *not* guarantee the application is immediately deployable.
It simply generates a CDK application which will synthesize a template that has identical resource configurations 
to the provided template. 

  - CDK Migrate does not interact with the CloudFormation service to verify the template 
provided can deploy on its own. This means CDK Migrate will not verify that any resources in the provided 
template are already managed in other CloudFormation templates, nor will it verify that the resources in the provided
template are available in the desired regions, which may impact ADC or Opt-In regions. 

  - If the provided template has parameters without default values, those will need to be provided
before deploying the generated application.

In practice this is how CDK Migrate generated applications will operate in the following scenarios:

| Situation                                                                                         | Result                                                                        |
| ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| Provided template + stack-name is from a deployed stack in the account/region                     | The CDK application will deploy as a changeset to the existing stack          |
| Provided template has no overlap with resources already in the account/region                     | The CDK application will deploy a new stack successfully                      |
| Provided template has overlap with Cloudformation managed resources already in the account/region | The CDK application will not be deployable unless those resources are removed |
| Provided template has overlap with un-managed resources already in the account/region              | The CDK application will not be deployable until those resources are adopted with [`cdk import`](#cdk-import) |
| No template has been provided and resources exist in the region the scan is done | The CDK application will be immediatly deployable and will import those resources into a new cloudformation stack upon deploy |

##### **The provided template is already deployed to CloudFormation in the account/region**

If the provided template came directly from a deployed CloudFormation stack, and that stack has not experienced any drift, 
then the generated application will be immediately deployable, and will not cause any changes to the deployed resources.
Drift might occur if a resource in your template was modified outside of CloudFormation, namely via the AWS Console or AWS CLI.

##### **The provided template is not deployed to CloudFormation in the account/region, and there *is not* overlap with existing resources in the account/region**

If the provided template represents a set of resources that have no overlap with resources already deployed in the account/region, 
then the generated application will be immediately deployable. This could be because the stack has never been deployed, or
the application was generated from a stack deployed in another account/region.

In practice this means for any resource in the provided template, for example,

```Json
    "S3Bucket": {
      "Type": "AWS::S3::Bucket",
      "Properties": {
        "BucketName": "MyBucket",
        "AccessControl": "PublicRead",
      },
      "DeletionPolicy": "Retain"
    }
```

There must not exist a resource of that type with the same identifier in the desired region. In this example that identfier 
would be "MyBucket"

##### **The provided template is not deployed to CloudFormation in the account/region, and there *is* overlap with existing resources in the account/region**

If the provided template represents a set of resources that overlap with resources already deployed in the account/region, 
then the generated application will not be immediately deployable. If those overlapped resources are already managed by 
another CloudFormation stack in that account/region, then those resources will need to be manually removed from the provided
template. Otherwise, if the overlapped resources are not managed by another CloudFormation stack, then first remove those
resources from your CDK Application Stack, deploy the cdk application successfully, then re-add them and run `cdk import` 
to import them into your deployed stack.
----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
  • Loading branch information
HBobertz authored and SankyRed committed Feb 8, 2024
1 parent 2a8f6b0 commit 8f36d5c
Show file tree
Hide file tree
Showing 9 changed files with 1,262 additions and 39 deletions.
5 changes: 5 additions & 0 deletions packages/@aws-cdk-testing/cli-integ/lib/with-cdk-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { AwsContext, withAws } from './with-aws';
import { withTimeout } from './with-timeout';

export const DEFAULT_TEST_TIMEOUT_S = 10 * 60;
export const EXTENDED_TEST_TIMEOUT_S = 30 * 60;

/**
* Higher order function to execute a block with a CDK app fixture
Expand Down Expand Up @@ -185,6 +186,10 @@ export function withDefaultFixture(block: (context: TestFixture) => Promise<void
return withAws(withTimeout(DEFAULT_TEST_TIMEOUT_S, withCdkApp(block)));
}

export function withExtendedTimeoutFixture(block: (context: TestFixture) => Promise<void>) {
return withAws(withTimeout(EXTENDED_TEST_TIMEOUT_S, withCdkApp(block)));
}

export function withCDKMigrateFixture(language: string, block: (content: TestFixture) => Promise<void>) {
return withAws(withTimeout(DEFAULT_TEST_TIMEOUT_S, withCdkMigrateApp(language, block)));
}
Expand Down
28 changes: 28 additions & 0 deletions packages/@aws-cdk-testing/cli-integ/resources/cdk-apps/app/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,35 @@ class MigrateStack extends cdk.Stack {
value: queue.node.defaultChild.logicalId,
});
}
if (process.env.SAMPLE_RESOURCES) {
const myTopic = new sns.Topic(this, 'migratetopic1', {
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
cdk.Tags.of(myTopic).add('tag1', 'value1');
const myTopic2 = new sns.Topic(this, 'migratetopic2', {
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
cdk.Tags.of(myTopic2).add('tag2', 'value2');
const myQueue = new sqs.Queue(this, 'migratequeue1', {
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
cdk.Tags.of(myQueue).add('tag3', 'value3');
}
if (process.env.LAMBDA_RESOURCES) {
const myFunction = new lambda.Function(this, 'migratefunction1', {
code: lambda.Code.fromInline('console.log("hello world")'),
handler: 'index.handler',
runtime: lambda.Runtime.NODEJS_18_X,
});
cdk.Tags.of(myFunction).add('lambda-tag', 'lambda-value');

const myFunction2 = new lambda.Function(this, 'migratefunction2', {
code: lambda.Code.fromInline('console.log("hello world2")'),
handler: 'index.handler',
runtime: lambda.Runtime.NODEJS_18_X,
});
cdk.Tags.of(myFunction2).add('lambda-tag', 'lambda-value');
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { promises as fs, existsSync } from 'fs';
import * as os from 'os';
import * as path from 'path';
import { integTest, cloneDirectory, shell, withDefaultFixture, retry, sleep, randomInteger, withSamIntegrationFixture, RESOURCES_DIR, withCDKMigrateFixture } from '../../lib';
import { integTest, cloneDirectory, shell, withDefaultFixture, retry, sleep, randomInteger, withSamIntegrationFixture, RESOURCES_DIR, withCDKMigrateFixture, withExtendedTimeoutFixture } from '../../lib';

jest.setTimeout(2 * 60 * 60_000); // Includes the time to acquire locks, worst-case single-threaded runtime

Expand Down Expand Up @@ -571,9 +571,9 @@ integTest('deploy with role', withDefaultFixture(async (fixture) => {
}
}));

// TODO add go back in when template synths properly
// TODO add more testing that ensures the symmetry of the generated constructs to the resources.
['typescript', 'python', 'csharp', 'java'].forEach(language => {
integTest(`cdk migrate ${language}`, withCDKMigrateFixture(language, async (fixture) => {
integTest(`cdk migrate ${language} deploys successfully`, withCDKMigrateFixture(language, async (fixture) => {
if (language === 'python') {
await fixture.shell(['pip', 'install', '-r', 'requirements.txt']);
}
Expand All @@ -588,6 +588,118 @@ integTest('deploy with role', withDefaultFixture(async (fixture) => {
}));
});

integTest('cdk migrate generates migrate.json', withCDKMigrateFixture('typescript', async (fixture) => {

const migrateFile = await fs.readFile(path.join(fixture.integTestDir, 'migrate.json'), 'utf8');
const expectedFile = `{
\"//\": \"This file is generated by cdk migrate. It will be automatically deleted after the first successful deployment of this app to the environment of the original resources.\",
\"Source\": \"localfile\"
}`;
expect(JSON.parse(migrateFile)).toEqual(JSON.parse(expectedFile));
await fixture.cdkDestroy(fixture.stackNamePrefix);
}));

integTest('cdk migrate --from-scan with AND/OR filters correctly filters resources', withExtendedTimeoutFixture(async (fixture) => {
const stackName = `cdk-migrate-integ-${fixture.randomString}`;

await fixture.cdkDeploy('migrate-stack', {
modEnv: { SAMPLE_RESOURCES: '1' },
});
await fixture.cdk(
['migrate', '--stack-name', stackName, '--from-scan', 'new', '--filter', 'type=AWS::SNS::Topic,tag-key=tag1', 'type=AWS::SQS::Queue,tag-key=tag3'],
{ modEnv: { MIGRATE_INTEG_TEST: '1' }, neverRequireApproval: true, verbose: true, captureStderr: false },
);

try {
const response = await fixture.aws.cloudFormation('describeGeneratedTemplate', {
GeneratedTemplateName: stackName,
});
const resourceNames = [];
for (const resource of response.Resources || []) {
if (resource.LogicalResourceId) {
resourceNames.push(resource.LogicalResourceId);
}
}
fixture.log(`Resources: ${resourceNames}`);
expect(resourceNames.some(ele => ele && ele.includes('migratetopic1'))).toBeTruthy();
expect(resourceNames.some(ele => ele && ele.includes('migratequeue1'))).toBeTruthy();
} finally {
await fixture.cdkDestroy('migrate-stack');
await fixture.aws.cloudFormation('deleteGeneratedTemplate', {
GeneratedTemplateName: stackName,
});
}
}));

integTest('cdk migrate --from-scan for resources with Write Only Properties generates warnings', withExtendedTimeoutFixture(async (fixture) => {
const stackName = `cdk-migrate-integ-${fixture.randomString}`;

await fixture.cdkDeploy('migrate-stack', {
modEnv: {
LAMBDA_RESOURCES: '1',
},
});
await fixture.cdk(
['migrate', '--stack-name', stackName, '--from-scan', 'new', '--filter', 'type=AWS::Lambda::Function,tag-key=lambda-tag'],
{ modEnv: { MIGRATE_INTEG_TEST: '1' }, neverRequireApproval: true, verbose: true, captureStderr: false },
);

try {

const response = await fixture.aws.cloudFormation('describeGeneratedTemplate', {
GeneratedTemplateName: stackName,
});
const resourceNames = [];
for (const resource of response.Resources || []) {
if (resource.LogicalResourceId && resource.ResourceType === 'AWS::Lambda::Function') {
resourceNames.push(resource.LogicalResourceId);
}
}
fixture.log(`Resources: ${resourceNames}`);
const readmePath = path.join(fixture.integTestDir, stackName, 'README.md');
const readme = await fs.readFile(readmePath, 'utf8');
expect(readme).toContain('## Warnings');
for (const resourceName of resourceNames) {
expect(readme).toContain(`### ${resourceName}`);
}
} finally {
await fixture.cdkDestroy('migrate-stack');
await fixture.aws.cloudFormation('deleteGeneratedTemplate', {
GeneratedTemplateName: stackName,
});
}
}));

['typescript', 'python', 'csharp', 'java'].forEach(language => {
integTest(`cdk migrate --from-stack creates deployable ${language} app`, withExtendedTimeoutFixture(async (fixture) => {
const migrateStackName = fixture.fullStackName('migrate-stack');
await fixture.aws.cloudFormation('createStack', {
StackName: migrateStackName,
TemplateBody: await fs.readFile(path.join(__dirname, '..', '..', 'resources', 'templates', 'sqs-template.json'), 'utf8'),
});
try {
let stackStatus = 'CREATE_IN_PROGRESS';
while (stackStatus === 'CREATE_IN_PROGRESS') {
stackStatus = await (await (fixture.aws.cloudFormation('describeStacks', { StackName: migrateStackName }))).Stacks?.[0].StackStatus!;
await sleep(1000);
}
await fixture.cdk(
['migrate', '--stack-name', migrateStackName, '--from-stack'],
{ modEnv: { MIGRATE_INTEG_TEST: '1' }, neverRequireApproval: true, verbose: true, captureStderr: false },
);
await fixture.shell(['cd', path.join(fixture.integTestDir, migrateStackName)]);
await fixture.cdk(['deploy', migrateStackName], { neverRequireApproval: true, verbose: true, captureStderr: false });
const response = await fixture.aws.cloudFormation('describeStacks', {
StackName: migrateStackName,
});

expect(response.Stacks?.[0].StackStatus).toEqual('UPDATE_COMPLETE');
} finally {
await fixture.cdkDestroy('migrate-stack');
}
}));
});

integTest('cdk diff', withDefaultFixture(async (fixture) => {
const diff1 = await fixture.cdk(['diff', fixture.fullStackName('test-1')]);
expect(diff1).toContain('AWS::SNS::Topic');
Expand Down
89 changes: 82 additions & 7 deletions packages/aws-cdk/lib/cdk-toolkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { findCloudWatchLogGroups } from './api/logs/find-cloudwatch-logs';
import { CloudWatchLogEventMonitor } from './api/logs/logs-monitor';
import { createDiffChangeSet, ResourcesToImport } from './api/util/cloudformation';
import { StackActivityProgress } from './api/util/cloudformation/stack-activity-monitor';
import { generateCdkApp, generateStack, readFromPath, readFromStack, setEnvironment, validateSourceOptions } from './commands/migrate';
import { generateCdkApp, generateStack, readFromPath, readFromStack, setEnvironment, parseSourceOptions, generateTemplate, FromScan, TemplateSourceOptions, GenerateTemplateOutput, CfnTemplateGeneratorProvider, writeMigrateJsonFile, buildGenertedTemplateOutput, buildCfnClient, appendWarningsToReadme, isThereAWarning } from './commands/migrate';
import { printSecurityDiff, printStackDiff, RequireApproval } from './diff';
import { ResourceImporter, removeNonImportResources } from './import';
import { data, debug, error, highlight, print, success, warning, withCorkedLogging } from './logging';
Expand Down Expand Up @@ -735,19 +735,80 @@ export class CdkToolkit {
public async migrate(options: MigrateOptions): Promise<void> {
warning('This is an experimental feature and development on it is still in progress. We make no guarantees about the outcome or stability of the functionality.');
const language = options.language?.toLowerCase() ?? 'typescript';
const environment = setEnvironment(options.account, options.region);
let generateTemplateOutput: GenerateTemplateOutput | undefined;
let cfn: CfnTemplateGeneratorProvider | undefined;
let templateToDelete: string | undefined;

try {
validateSourceOptions(options.fromPath, options.fromStack);
const template = readFromPath(options.fromPath) ||
await readFromStack(options.stackName, this.props.sdkProvider, setEnvironment(options.account, options.region));
const stack = generateStack(template!, options.stackName, language);
// if neither fromPath nor fromStack is provided, generate a template using cloudformation
const scanType = parseSourceOptions(options.fromPath, options.fromStack, options.stackName).source;
if (scanType == TemplateSourceOptions.SCAN) {
generateTemplateOutput = await generateTemplate({
stackName: options.stackName,
filters: options.filter,
fromScan: options.fromScan,
sdkProvider: this.props.sdkProvider,
environment: environment,
});
templateToDelete = generateTemplateOutput.templateId;
} else if (scanType == TemplateSourceOptions.PATH) {
const templateBody = readFromPath(options.fromPath!);

const parsedTemplate = deserializeStructure(templateBody);
const templateId = parsedTemplate.Metadata?.TemplateId?.toString();
if (templateId) {
// if we have a template id, we can call describe generated template to get the resource identifiers
// resource metadata, and template source to generate the template
cfn = new CfnTemplateGeneratorProvider(await buildCfnClient(this.props.sdkProvider, environment));
const generatedTemplateSummary = await cfn.describeGeneratedTemplate(templateId);
generateTemplateOutput = buildGenertedTemplateOutput(generatedTemplateSummary, templateBody, generatedTemplateSummary.GeneratedTemplateId!);
} else {
generateTemplateOutput = {
migrateJson: {
templateBody: templateBody,
source: 'localfile',
},
};
}
} else if (scanType == TemplateSourceOptions.STACK) {
const template = await readFromStack(options.stackName, this.props.sdkProvider, environment);
if (!template) {
throw new Error(`No template found for stack-name: ${options.stackName}`);
}
generateTemplateOutput = {
migrateJson: {
templateBody: template,
source: options.stackName,
},
};
} else {
// We shouldn't ever get here, but just in case.
throw new Error(`Invalid source option provided: ${scanType}`);
}
const stack = generateStack(generateTemplateOutput.migrateJson.templateBody, options.stackName, language);
success(' ⏳ Generating CDK app for %s...', chalk.blue(options.stackName));
await generateCdkApp(options.stackName, stack!, language, options.outputPath, options.compress);
if (generateTemplateOutput) {
writeMigrateJsonFile(options.outputPath, options.stackName, generateTemplateOutput.migrateJson);
}
if (isThereAWarning(generateTemplateOutput)) {
warning(' ⚠️ Some resources could not be migrated completely. Please review the README.md file for more information.');
appendWarningsToReadme(`${path.join(options.outputPath ?? process.cwd(), options.stackName)}/README.md`, generateTemplateOutput.resources!);
}
} catch (e) {
error(' ❌ Migrate failed for `%s`: %s', chalk.blue(options.stackName), (e as Error).message);
error(' ❌ Migrate failed for `%s`: %s', options.stackName, (e as Error).message);
throw e;
} finally {
if (templateToDelete) {
if (!cfn) {
cfn = new CfnTemplateGeneratorProvider(await buildCfnClient(this.props.sdkProvider, environment));
}
if (!process.env.MIGRATE_INTEG_TEST) {
await cfn.deleteGeneratedTemplate(templateToDelete);
}
}
}

}

private async selectStacksForList(patterns: string[]) {
Expand Down Expand Up @@ -1353,6 +1414,20 @@ export interface MigrateOptions {
*/
readonly region?: string;

/**
* Filtering criteria used to select the resources to be included in the generated CDK app.
*
* @default - Include all resources
*/
readonly filter?: string[];

/**
* Whether to initiate a new account scan for generating the CDK app.
*
* @default false
*/
readonly fromScan?: FromScan;

/**
* Whether to zip the generated cdk app folder.
*
Expand Down
19 changes: 18 additions & 1 deletion packages/aws-cdk/lib/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { CdkToolkit, AssetBuildTime } from '../lib/cdk-toolkit';
import { realHandler as context } from '../lib/commands/context';
import { realHandler as docs } from '../lib/commands/docs';
import { realHandler as doctor } from '../lib/commands/doctor';
import { MIGRATE_SUPPORTED_LANGUAGES } from '../lib/commands/migrate';
import { MIGRATE_SUPPORTED_LANGUAGES, getMigrateScanType } from '../lib/commands/migrate';
import { RequireApproval } from '../lib/diff';
import { availableInitLanguages, cliInit, printAvailableTemplates } from '../lib/init';
import { data, debug, error, print, setLogLevel, setCI } from '../lib/logging';
Expand Down Expand Up @@ -281,6 +281,21 @@ async function parseCommandLineArguments(args: string[]) {
.option('from-path', { type: 'string', desc: 'The path to the CloudFormation template to migrate. Use this for locally stored templates' })
.option('from-stack', { type: 'boolean', desc: 'Use this flag to retrieve the template for an existing CloudFormation stack' })
.option('output-path', { type: 'string', desc: 'The output path for the migrated CDK app' })
.option('from-scan', {
type: 'string',
desc: 'Determines if a new scan should be created, or the last successful existing scan should be used ' +
'\n options are "new" or "most-recent"',
})
.option('filter', {
type: 'array',
desc: 'Filters the resource scan based on the provided criteria in the following format: "key1=value1,key2=value2"' +
'\n This field can be passed multiple times for OR style filtering: ' +
'\n filtering options: ' +
'\n resource-identifier: A key-value pair that identifies the target resource. i.e. {"ClusterName", "myCluster"}' +
'\n resource-type-prefix: A string that represents a type-name prefix. i.e. "AWS::DynamoDB::"' +
'\n tag-key: a string that matches resources with at least one tag with the provided key. i.e. "myTagKey"' +
'\n tag-value: a string that matches resources with at least one tag with the provided value. i.e. "myTagValue"',
})
.option('compress', { type: 'boolean', desc: 'Use this flag to zip the generated CDK app' }),
)
.command('context', 'Manage cached context values', (yargs: Argv) => yargs
Expand Down Expand Up @@ -679,6 +694,8 @@ export async function exec(args: string[], synthesizer?: Synthesizer): Promise<n
fromStack: args['from-stack'],
language: args.language,
outputPath: args['output-path'],
fromScan: getMigrateScanType(args['from-scan']),
filter: args.filter,
account: args.account,
region: args.region,
compress: args.compress,
Expand Down
Loading

0 comments on commit 8f36d5c

Please sign in to comment.