-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathcdk-toolkit.ts
More file actions
2316 lines (2024 loc) · 79.2 KB
/
cdk-toolkit.ts
File metadata and controls
2316 lines (2024 loc) · 79.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as path from 'path';
import { format } from 'util';
import { RequireApproval } from '@aws-cdk/cloud-assembly-schema';
import * as cxapi from '@aws-cdk/cx-api';
import type { ConfirmationRequest, DeploymentMethod, ToolkitAction, ToolkitOptions } from '@aws-cdk/toolkit-lib';
import { PermissionChangeType, Toolkit, ToolkitError } from '@aws-cdk/toolkit-lib';
import * as chalk from 'chalk';
import * as chokidar from 'chokidar';
import * as fs from 'fs-extra';
import * as uuid from 'uuid';
import { CliIoHost } from './io-host';
import type { Configuration } from './user-configuration';
import { PROJECT_CONFIG } from './user-configuration';
import type { ActionLessRequest, IoHelper } from '../../lib/api-private';
import { asIoHelper, cfnApi, IO, tagsForStack } from '../../lib/api-private';
import type { AssetBuildNode, AssetPublishNode, Concurrency, StackNode, WorkGraph } from '../api';
import {
CloudWatchLogEventMonitor,
DEFAULT_TOOLKIT_STACK_NAME,
DiffFormatter,
findCloudWatchLogGroups,
GarbageCollector,
removeNonImportResources,
ResourceImporter,
ResourceMigrator,
StackSelectionStrategy,
WorkGraphBuilder,
} from '../api';
import type { SdkProvider } from '../api/aws-auth';
import type { BootstrapEnvironmentOptions } from '../api/bootstrap';
import { Bootstrapper } from '../api/bootstrap';
import { ExtendedStackSelection, StackCollection } from '../api/cloud-assembly';
import type { Deployments, SuccessfulDeployStackResult } from '../api/deployments';
import { mappingsByEnvironment, parseMappingGroups } from '../api/refactor';
import { type Tag } from '../api/tags';
import { StackActivityProgress } from '../commands/deploy';
import { listResources, explainResource } from '../commands/list-resources';
import { listStacks } from '../commands/list-stacks';
import type { FromScan, GenerateTemplateOutput } from '../commands/migrate';
import {
appendWarningsToReadme,
buildCfnClient,
buildGeneratedTemplateOutput,
CfnTemplateGeneratorProvider,
generateCdkApp,
generateStack,
generateTemplate,
isThereAWarning,
parseSourceOptions,
readFromPath,
readFromStack,
setEnvironment,
TemplateSourceOptions,
writeMigrateJsonFile,
} from '../commands/migrate';
import type { CloudAssembly, CloudExecutable, StackSelector } from '../cxapp';
import { DefaultSelection, environmentsFromDescriptors, globEnvironmentsFromStacks, looksLikeGlob } from '../cxapp';
import { OBSOLETE_FLAGS } from '../obsolete-flags';
import {
deserializeStructure,
formatErrorMessage,
formatTime,
obscureTemplate,
partition,
serializeStructure,
validateSnsTopicArn,
} from '../util';
import { canCollectTelemetry } from './telemetry/collect-telemetry';
import { cdkCliErrorName } from './telemetry/error';
import { CLI_PRIVATE_SPAN } from './telemetry/messages';
import type { ErrorDetails } from './telemetry/schema';
// Must use a require() otherwise esbuild complains about calling a namespace
// eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/consistent-type-imports
const pLimit: typeof import('p-limit') = require('p-limit');
export interface CdkToolkitProps {
/**
* The Cloud Executable
*/
cloudExecutable: CloudExecutable;
/**
* The provisioning engine used to apply changes to the cloud
*/
deployments: Deployments;
/**
* The CliIoHost that's used for I/O operations
*/
ioHost?: CliIoHost;
/**
* Name of the toolkit stack to use/deploy
*
* @default CDKToolkit
*/
toolkitStackName?: string;
/**
* Whether to be verbose
*
* @default false
*/
verbose?: boolean;
/**
* Don't stop on error metadata
*
* @default false
*/
ignoreErrors?: boolean;
/**
* Treat warnings in metadata as errors
*
* @default false
*/
strict?: boolean;
/**
* Application configuration (settings and context)
*/
configuration: Configuration;
/**
* AWS object (used by synthesizer and contextprovider)
*/
sdkProvider: SdkProvider;
}
/**
* When to build assets
*/
export enum AssetBuildTime {
/**
* Build all assets before deploying the first stack
*
* This is intended for expensive Docker image builds; so that if the Docker image build
* fails, no stacks are unnecessarily deployed (with the attendant wait time).
*/
ALL_BEFORE_DEPLOY = 'all-before-deploy',
/**
* Build assets just-in-time, before publishing
*/
JUST_IN_TIME = 'just-in-time',
}
/**
* Custom implementation of the public Toolkit to integrate with the legacy CdkToolkit
*
* This overwrites how an sdkProvider is acquired
* in favor of the one provided directly to CdkToolkit.
*/
class InternalToolkit extends Toolkit {
private readonly _sdkProvider: SdkProvider;
public constructor(sdkProvider: SdkProvider, options: Omit<ToolkitOptions, 'sdkConfig'>) {
super(options);
this._sdkProvider = sdkProvider;
}
/**
* Access to the AWS SDK
* @internal
*/
protected async sdkProvider(_action: ToolkitAction): Promise<SdkProvider> {
return this._sdkProvider;
}
}
/**
* Toolkit logic
*
* The toolkit runs the `cloudExecutable` to obtain a cloud assembly and
* deploys applies them to `cloudFormation`.
*/
export class CdkToolkit {
private ioHost: CliIoHost;
private toolkitStackName: string;
private toolkit: InternalToolkit;
constructor(private readonly props: CdkToolkitProps) {
this.ioHost = props.ioHost ?? CliIoHost.instance();
this.toolkitStackName = props.toolkitStackName ?? DEFAULT_TOOLKIT_STACK_NAME;
this.toolkit = new InternalToolkit(props.sdkProvider, {
assemblyFailureAt: this.validateMetadataFailAt(),
color: true,
emojis: true,
ioHost: this.ioHost,
toolkitStackName: this.toolkitStackName,
unstableFeatures: ['refactor', 'flags'],
});
}
public async metadata(stackName: string, json: boolean) {
const stacks = await this.selectSingleStackByName(stackName);
await printSerializedObject(this.ioHost.asIoHelper(), stacks.firstStack.manifest.metadata ?? {}, json);
}
public async acknowledge(noticeId: string) {
const acks = new Set(this.props.configuration.context.get('acknowledged-issue-numbers') ?? []);
acks.add(Number(noticeId));
this.props.configuration.context.set('acknowledged-issue-numbers', Array.from(acks));
await this.props.configuration.saveContext();
}
public async cliTelemetryStatus(versionReporting: boolean = true) {
// recreate the version-reporting property in args rather than bring the entire args object over
const args = { ['version-reporting']: versionReporting };
const canCollect = canCollectTelemetry(args, this.props.configuration.context);
if (canCollect) {
await this.ioHost.asIoHelper().defaults.info('CLI Telemetry is enabled. See https://docs.aws.amazon.com/cdk/v2/guide/cli-telemetry.html for ways to disable.');
} else {
await this.ioHost.asIoHelper().defaults.info('CLI Telemetry is disabled. See https://docs.aws.amazon.com/cdk/v2/guide/cli-telemetry.html for ways to enable.');
}
}
public async cliTelemetry(enable: boolean) {
this.props.configuration.context.set('cli-telemetry', enable);
await this.props.configuration.saveContext();
await this.ioHost.asIoHelper().defaults.info(`Telemetry ${enable ? 'enabled' : 'disabled'}`);
}
public async diff(options: DiffOptions): Promise<number> {
const stacks = await this.selectStacksForDiff(options.stackNames, options.exclusively);
const strict = !!options.strict;
const contextLines = options.contextLines || 3;
const quiet = options.quiet || false;
let diffs = 0;
const parameterMap = buildParameterMap(options.parameters);
if (options.templatePath !== undefined) {
// Compare single stack against fixed template
if (stacks.stackCount !== 1) {
throw new ToolkitError(
'Can only select one stack when comparing to fixed template. Use --exclusively to avoid selecting multiple stacks.',
);
}
if (!(await fs.pathExists(options.templatePath))) {
throw new ToolkitError(`There is no file at ${options.templatePath}`);
}
if (options.importExistingResources) {
throw new ToolkitError(
'Can only use --import-existing-resources flag when comparing against deployed stacks.',
);
}
const template = deserializeStructure(await fs.readFile(options.templatePath, { encoding: 'UTF-8' }));
const formatter = new DiffFormatter({
templateInfo: {
oldTemplate: template,
newTemplate: stacks.firstStack,
},
});
if (options.securityOnly) {
const securityDiff = formatter.formatSecurityDiff();
// Warn, count, and display the diff only if the reported changes are broadening permissions
if (securityDiff.permissionChangeType === PermissionChangeType.BROADENING) {
await this.ioHost.asIoHelper().defaults.warn('This deployment will make potentially sensitive changes according to your current security approval level.\nPlease confirm you intend to make the following modifications:\n');
await this.ioHost.asIoHelper().defaults.info(securityDiff.formattedDiff);
diffs += 1;
}
} else {
const diff = formatter.formatStackDiff({
strict,
contextLines,
quiet,
});
diffs = diff.numStacksWithChanges;
await this.ioHost.asIoHelper().defaults.info(diff.formattedDiff);
}
} else {
const allMappings = options.includeMoves
? await mappingsByEnvironment(stacks.stackArtifacts, this.props.sdkProvider, true)
: [];
// Compare N stacks against deployed templates
for (const stack of stacks.stackArtifacts) {
const templateWithNestedStacks = await this.props.deployments.readCurrentTemplateWithNestedStacks(
stack,
options.compareAgainstProcessedTemplate,
);
const currentTemplate = templateWithNestedStacks.deployedRootTemplate;
const nestedStacks = templateWithNestedStacks.nestedStacks;
const migrator = new ResourceMigrator({
deployments: this.props.deployments,
ioHelper: asIoHelper(this.ioHost, 'diff'),
});
const resourcesToImport = await migrator.tryGetResources(await this.props.deployments.resolveEnvironment(stack));
if (resourcesToImport) {
removeNonImportResources(stack);
}
let changeSet = undefined;
if (options.changeSet) {
let stackExists = false;
try {
stackExists = await this.props.deployments.stackExists({
stack,
deployName: stack.stackName,
tryLookupRole: true,
});
} catch (e: any) {
await this.ioHost.asIoHelper().defaults.debug(formatErrorMessage(e));
if (!quiet) {
await this.ioHost.asIoHelper().defaults.info(
`Checking if the stack ${stack.stackName} exists before creating the changeset has failed, will base the diff on template differences (run again with -v to see the reason)\n`,
);
}
stackExists = false;
}
if (stackExists) {
changeSet = await cfnApi.createDiffChangeSet(asIoHelper(this.ioHost, 'diff'), {
stack,
uuid: uuid.v4(),
deployments: this.props.deployments,
willExecute: false,
sdkProvider: this.props.sdkProvider,
parameters: Object.assign({}, parameterMap['*'], parameterMap[stack.stackName]),
resourcesToImport,
importExistingResources: options.importExistingResources,
});
} else {
await this.ioHost.asIoHelper().defaults.debug(
`the stack '${stack.stackName}' has not been deployed to CloudFormation or describeStacks call failed, skipping changeset creation.`,
);
}
}
const mappings = allMappings.find(m =>
m.environment.region === stack.environment.region && m.environment.account === stack.environment.account,
)?.mappings ?? {};
const formatter = new DiffFormatter({
templateInfo: {
oldTemplate: currentTemplate,
newTemplate: stack,
changeSet,
isImport: !!resourcesToImport,
nestedStacks,
mappings,
},
});
if (options.securityOnly) {
const securityDiff = formatter.formatSecurityDiff();
// Warn, count, and display the diff only if the reported changes are broadening permissions
if (securityDiff.permissionChangeType === PermissionChangeType.BROADENING) {
await this.ioHost.asIoHelper().defaults.warn('This deployment will make potentially sensitive changes according to your current security approval level.\nPlease confirm you intend to make the following modifications:\n');
await this.ioHost.asIoHelper().defaults.info(securityDiff.formattedDiff);
diffs += 1;
}
} else {
const diff = formatter.formatStackDiff({
strict,
contextLines,
quiet,
});
await this.ioHost.asIoHelper().defaults.info(diff.formattedDiff);
diffs += diff.numStacksWithChanges;
}
}
}
await this.ioHost.asIoHelper().defaults.info(format('\n✨ Number of stacks with differences: %s\n', diffs));
return diffs && options.fail ? 1 : 0;
}
public async deploy(options: DeployOptions) {
if (options.watch) {
return this.watch(options);
}
// set progress from options, this includes user and app config
if (options.progress) {
this.ioHost.stackProgress = options.progress;
}
const startSynthTime = new Date().getTime();
const stackCollection = await this.selectStacksForDeploy(
options.selector,
options.exclusively,
options.cacheCloudAssembly,
options.ignoreNoStacks,
);
const elapsedSynthTime = new Date().getTime() - startSynthTime;
await this.ioHost.asIoHelper().defaults.info(`\n✨ Synthesis time: ${formatTime(elapsedSynthTime)}s\n`);
if (stackCollection.stackCount === 0) {
await this.ioHost.asIoHelper().defaults.error('This app contains no stacks');
return;
}
const migrator = new ResourceMigrator({
deployments: this.props.deployments,
ioHelper: asIoHelper(this.ioHost, 'deploy'),
});
await migrator.tryMigrateResources(stackCollection, {
toolkitStackName: this.toolkitStackName,
...options,
});
const requireApproval = options.requireApproval ?? RequireApproval.BROADENING;
const parameterMap = buildParameterMap(options.parameters);
if (options.deploymentMethod?.method === 'hotswap') {
await this.ioHost.asIoHelper().defaults.warn(
'⚠️ The --hotswap and --hotswap-fallback flags deliberately introduce CloudFormation drift to speed up deployments',
);
await this.ioHost.asIoHelper().defaults.warn('⚠️ They should only be used for development - never use them for your production Stacks!\n');
}
const stacks = stackCollection.stackArtifacts;
const stackOutputs: { [key: string]: any } = {};
const outputsFile = options.outputsFile;
const buildAsset = async (assetNode: AssetBuildNode) => {
await this.props.deployments.buildSingleAsset(
assetNode.assetManifestArtifact,
assetNode.assetManifest,
assetNode.asset,
{
stack: assetNode.parentStack,
roleArn: options.roleArn,
stackName: assetNode.parentStack.stackName,
},
);
};
const publishAsset = async (assetNode: AssetPublishNode) => {
await this.props.deployments.publishSingleAsset(assetNode.assetManifest, assetNode.asset, {
stack: assetNode.parentStack,
roleArn: options.roleArn,
stackName: assetNode.parentStack.stackName,
forcePublish: options.force,
});
};
const deployStack = async (stackNode: StackNode) => {
const stack = stackNode.stack;
if (stackCollection.stackCount !== 1) {
await this.ioHost.asIoHelper().defaults.info(chalk.bold(stack.displayName));
}
if (!stack.environment) {
// eslint-disable-next-line @stylistic/max-len
throw new ToolkitError(
`Stack ${stack.displayName} does not define an environment, and AWS credentials could not be obtained from standard locations or no region was configured.`,
);
}
if (Object.keys(stack.template.Resources || {}).length === 0) {
// The generated stack has no resources
if (!(await this.props.deployments.stackExists({ stack }))) {
await this.ioHost.asIoHelper().defaults.warn('%s: stack has no resources, skipping deployment.', chalk.bold(stack.displayName));
} else {
await this.ioHost.asIoHelper().defaults.warn('%s: stack has no resources, deleting existing stack.', chalk.bold(stack.displayName));
await this.destroy({
selector: { patterns: [stack.hierarchicalId] },
exclusively: true,
force: true,
roleArn: options.roleArn,
fromDeploy: true,
});
}
return;
}
if (requireApproval !== RequireApproval.NEVER) {
const currentTemplate = await this.props.deployments.readCurrentTemplate(stack);
const formatter = new DiffFormatter({
templateInfo: {
oldTemplate: currentTemplate,
newTemplate: stack,
},
});
const securityDiff = formatter.formatSecurityDiff();
if (requiresApproval(requireApproval, securityDiff.permissionChangeType)) {
const motivation = '"--require-approval" is enabled and stack includes security-sensitive updates';
await this.ioHost.asIoHelper().defaults.info(securityDiff.formattedDiff);
await askUserConfirmation(
this.ioHost,
IO.CDK_TOOLKIT_I5060.req(`${motivation}: 'Do you wish to deploy these changes'`, {
motivation,
concurrency,
permissionChangeType: securityDiff.permissionChangeType,
templateDiffs: formatter.diffs,
}),
);
}
}
// Following are the same semantics we apply with respect to Notification ARNs (dictated by the SDK)
//
// - undefined => cdk ignores it, as if it wasn't supported (allows external management).
// - []: => cdk manages it, and the user wants to wipe it out.
// - ['arn-1'] => cdk manages it, and the user wants to set it to ['arn-1'].
const notificationArns = (!!options.notificationArns || !!stack.notificationArns)
? (options.notificationArns ?? []).concat(stack.notificationArns ?? [])
: undefined;
for (const notificationArn of notificationArns ?? []) {
if (!validateSnsTopicArn(notificationArn)) {
throw new ToolkitError(`Notification arn ${notificationArn} is not a valid arn for an SNS topic`);
}
}
const stackIndex = stacks.indexOf(stack) + 1;
await this.ioHost.asIoHelper().defaults.info(`${chalk.bold(stack.displayName)}: deploying... [${stackIndex}/${stackCollection.stackCount}]`);
const startDeployTime = new Date().getTime();
let tags = options.tags;
if (!tags || tags.length === 0) {
tags = tagsForStack(stack);
}
// There is already a startDeployTime constant, but that does not work with telemetry.
// We should integrate the two in the future
const deploySpan = await this.ioHost.asIoHelper().span(CLI_PRIVATE_SPAN.DEPLOY).begin({});
let error: ErrorDetails | undefined;
let elapsedDeployTime = 0;
try {
let deployResult: SuccessfulDeployStackResult | undefined;
let rollback = options.rollback;
let iteration = 0;
while (!deployResult) {
if (++iteration > 2) {
throw new ToolkitError('This loop should have stabilized in 2 iterations, but didn\'t. If you are seeing this error, please report it at https://github.com/aws/aws-cdk/issues/new/choose');
}
const r = await this.props.deployments.deployStack({
stack,
deployName: stack.stackName,
roleArn: options.roleArn,
toolkitStackName: options.toolkitStackName,
reuseAssets: options.reuseAssets,
notificationArns,
tags,
execute: options.execute,
changeSetName: options.changeSetName,
deploymentMethod: options.deploymentMethod,
forceDeployment: options.force,
parameters: Object.assign({}, parameterMap['*'], parameterMap[stack.stackName]),
usePreviousParameters: options.usePreviousParameters,
rollback,
extraUserAgent: options.extraUserAgent,
assetParallelism: options.assetParallelism,
ignoreNoStacks: options.ignoreNoStacks,
});
switch (r.type) {
case 'did-deploy-stack':
deployResult = r;
break;
case 'failpaused-need-rollback-first': {
const motivation = r.reason === 'replacement'
? `Stack is in a paused fail state (${r.status}) and change includes a replacement which cannot be deployed with "--no-rollback"`
: `Stack is in a paused fail state (${r.status}) and command line arguments do not include "--no-rollback"`;
if (options.force) {
await this.ioHost.asIoHelper().defaults.warn(`${motivation}. Rolling back first (--force).`);
} else {
await askUserConfirmation(
this.ioHost,
IO.CDK_TOOLKIT_I5050.req(`${motivation}. Roll back first and then proceed with deployment`, {
motivation,
concurrency,
}),
);
}
// Perform a rollback
await this.rollback({
selector: { patterns: [stack.hierarchicalId] },
toolkitStackName: options.toolkitStackName,
force: options.force,
});
// Go around through the 'while' loop again but switch rollback to true.
rollback = true;
break;
}
case 'replacement-requires-rollback': {
const motivation = 'Change includes a replacement which cannot be deployed with "--no-rollback"';
if (options.force) {
await this.ioHost.asIoHelper().defaults.warn(`${motivation}. Proceeding with regular deployment (--force).`);
} else {
await askUserConfirmation(
this.ioHost,
IO.CDK_TOOLKIT_I5050.req(`${motivation}. Perform a regular deployment`, {
concurrency,
motivation,
}),
);
}
// Go around through the 'while' loop again but switch rollback to true.
rollback = true;
break;
}
default:
throw new ToolkitError(`Unexpected result type from deployStack: ${JSON.stringify(r)}. If you are seeing this error, please report it at https://github.com/aws/aws-cdk/issues/new/choose`);
}
}
const message = deployResult.noOp
? ' ✅ %s (no changes)'
: ' ✅ %s';
await this.ioHost.asIoHelper().defaults.info(chalk.green('\n' + message), stack.displayName);
elapsedDeployTime = new Date().getTime() - startDeployTime;
await this.ioHost.asIoHelper().defaults.info(`\n✨ Deployment time: ${formatTime(elapsedDeployTime)}s\n`);
if (Object.keys(deployResult.outputs).length > 0) {
await this.ioHost.asIoHelper().defaults.info('Outputs:');
stackOutputs[stack.stackName] = deployResult.outputs;
}
for (const name of Object.keys(deployResult.outputs).sort()) {
const value = deployResult.outputs[name];
await this.ioHost.asIoHelper().defaults.info(`${chalk.cyan(stack.id)}.${chalk.cyan(name)} = ${chalk.underline(chalk.cyan(value))}`);
}
await this.ioHost.asIoHelper().defaults.info('Stack ARN:');
await this.ioHost.asIoHelper().defaults.result(deployResult.stackArn);
} catch (e: any) {
// It has to be exactly this string because an integration test tests for
// "bold(stackname) failed: ResourceNotReady: <error>"
const wrappedError = new ToolkitError(
[`❌ ${chalk.bold(stack.stackName)} failed:`, ...(e.name ? [`${e.name}:`] : []), formatErrorMessage(e)].join(' '),
);
error = {
name: cdkCliErrorName(wrappedError.name),
};
throw wrappedError;
} finally {
await deploySpan.end({ error });
if (options.cloudWatchLogMonitor) {
const foundLogGroupsResult = await findCloudWatchLogGroups(this.props.sdkProvider, asIoHelper(this.ioHost, 'deploy'), stack);
options.cloudWatchLogMonitor.addLogGroups(
foundLogGroupsResult.env,
foundLogGroupsResult.sdk,
foundLogGroupsResult.logGroupNames,
);
}
// If an outputs file has been specified, create the file path and write stack outputs to it once.
// Outputs are written after all stacks have been deployed. If a stack deployment fails,
// all of the outputs from successfully deployed stacks before the failure will still be written.
if (outputsFile) {
fs.ensureFileSync(outputsFile);
await fs.writeJson(outputsFile, stackOutputs, {
spaces: 2,
encoding: 'utf8',
});
}
}
await this.ioHost.asIoHelper().defaults.info(`\n✨ Total time: ${formatTime(elapsedSynthTime + elapsedDeployTime)}s\n`);
};
const assetBuildTime = options.assetBuildTime ?? AssetBuildTime.ALL_BEFORE_DEPLOY;
const prebuildAssets = assetBuildTime === AssetBuildTime.ALL_BEFORE_DEPLOY;
const concurrency = options.concurrency || 1;
if (concurrency > 1) {
// always force "events" progress output when we have concurrency
this.ioHost.stackProgress = StackActivityProgress.EVENTS;
// ...but only warn if the user explicitly requested "bar" progress
if (options.progress && options.progress != StackActivityProgress.EVENTS) {
await this.ioHost.asIoHelper().defaults.warn('⚠️ The --concurrency flag only supports --progress "events". Switching to "events".');
}
}
const stacksAndTheirAssetManifests = stacks.flatMap((stack) => [
stack,
...stack.dependencies.filter(x => cxapi.AssetManifestArtifact.isAssetManifestArtifact(x)),
]);
const workGraph = new WorkGraphBuilder(
asIoHelper(this.ioHost, 'deploy'),
prebuildAssets,
).build(stacksAndTheirAssetManifests);
// Unless we are running with '--force', skip already published assets
if (!options.force) {
await this.removePublishedAssets(workGraph, options);
}
const graphConcurrency: Concurrency = {
'stack': concurrency,
'asset-build': 1, // This will be CPU-bound/memory bound, mostly matters for Docker builds
'asset-publish': (options.assetParallelism ?? true) ? 8 : 1, // This will be I/O-bound, 8 in parallel seems reasonable
};
await workGraph.doParallel(graphConcurrency, {
deployStack,
buildAsset,
publishAsset,
});
}
/**
* Detect infrastructure drift for the given stack(s)
*/
public async drift(options: DriftOptions): Promise<number> {
const driftResults = await this.toolkit.drift(this.props.cloudExecutable, {
stacks: {
patterns: options.selector.patterns,
strategy: options.selector.patterns.length > 0 ? StackSelectionStrategy.PATTERN_MATCH : StackSelectionStrategy.ALL_STACKS,
},
});
const totalDrifts = Object.values(driftResults).reduce((total, current) => total + (current.numResourcesWithDrift ?? 0), 0);
return totalDrifts > 0 && options.fail ? 1 : 0;
}
/**
* Roll back the given stack or stacks.
*/
public async rollback(options: RollbackOptions) {
const startSynthTime = new Date().getTime();
const stackCollection = await this.selectStacksForDeploy(options.selector, true);
const elapsedSynthTime = new Date().getTime() - startSynthTime;
await this.ioHost.asIoHelper().defaults.info(`\n✨ Synthesis time: ${formatTime(elapsedSynthTime)}s\n`);
if (stackCollection.stackCount === 0) {
await this.ioHost.asIoHelper().defaults.error('No stacks selected');
return;
}
let anyRollbackable = false;
for (const stack of stackCollection.stackArtifacts) {
await this.ioHost.asIoHelper().defaults.info('Rolling back %s', chalk.bold(stack.displayName));
const startRollbackTime = new Date().getTime();
try {
const result = await this.props.deployments.rollbackStack({
stack,
roleArn: options.roleArn,
toolkitStackName: options.toolkitStackName,
orphanFailedResources: options.force,
validateBootstrapStackVersion: options.validateBootstrapStackVersion,
orphanLogicalIds: options.orphanLogicalIds,
});
if (!result.notInRollbackableState) {
anyRollbackable = true;
}
const elapsedRollbackTime = new Date().getTime() - startRollbackTime;
await this.ioHost.asIoHelper().defaults.info(`\n✨ Rollback time: ${formatTime(elapsedRollbackTime).toString()}s\n`);
} catch (e: any) {
await this.ioHost.asIoHelper().defaults.error('\n ❌ %s failed: %s', chalk.bold(stack.displayName), formatErrorMessage(e));
throw new ToolkitError('Rollback failed (use --force to orphan failing resources)');
}
}
if (!anyRollbackable) {
throw new ToolkitError('No stacks were in a state that could be rolled back');
}
}
public async watch(options: WatchOptions) {
const rootDir = path.dirname(path.resolve(PROJECT_CONFIG));
const ioHelper = asIoHelper(this.ioHost, 'watch');
await this.ioHost.asIoHelper().defaults.debug("root directory used for 'watch' is: %s", rootDir);
const watchSettings: { include?: string | string[]; exclude: string | string[] } | undefined =
this.props.configuration.settings.get(['watch']);
if (!watchSettings) {
throw new ToolkitError(
"Cannot use the 'watch' command without specifying at least one directory to monitor. " +
'Make sure to add a "watch" key to your cdk.json',
);
}
// For the "include" subkey under the "watch" key, the behavior is:
// 1. No "watch" setting? We error out.
// 2. "watch" setting without an "include" key? We default to observing "./**".
// 3. "watch" setting with an empty "include" key? We default to observing "./**".
// 4. Non-empty "include" key? Just use the "include" key.
const watchIncludes = this.patternsArrayForWatch(watchSettings.include, {
rootDir,
returnRootDirIfEmpty: true,
});
await this.ioHost.asIoHelper().defaults.debug("'include' patterns for 'watch': %s", watchIncludes);
// For the "exclude" subkey under the "watch" key,
// the behavior is to add some default excludes in addition to the ones specified by the user:
// 1. The CDK output directory.
// 2. Any file whose name starts with a dot.
// 3. Any directory's content whose name starts with a dot.
// 4. Any node_modules and its content (even if it's not a JS/TS project, you might be using a local aws-cli package)
const outputDir = this.props.configuration.settings.get(['output']);
const watchExcludes = this.patternsArrayForWatch(watchSettings.exclude, {
rootDir,
returnRootDirIfEmpty: false,
}).concat(`${outputDir}/**`, '**/.*', '**/.*/**', '**/node_modules/**');
await this.ioHost.asIoHelper().defaults.debug("'exclude' patterns for 'watch': %s", watchExcludes);
// Since 'cdk deploy' is a relatively slow operation for a 'watch' process,
// introduce a concurrency latch that tracks the state.
// This way, if file change events arrive when a 'cdk deploy' is still executing,
// we will batch them, and trigger another 'cdk deploy' after the current one finishes,
// making sure 'cdk deploy's always execute one at a time.
// Here's a diagram showing the state transitions:
// -------------- -------- file changed -------------- file changed -------------- file changed
// | | ready event | | ------------------> | | ------------------> | | --------------|
// | pre-ready | -------------> | open | | deploying | | queued | |
// | | | | <------------------ | | <------------------ | | <-------------|
// -------------- -------- 'cdk deploy' done -------------- 'cdk deploy' done --------------
let latch: 'pre-ready' | 'open' | 'deploying' | 'queued' = 'pre-ready';
const cloudWatchLogMonitor = options.traceLogs ? new CloudWatchLogEventMonitor({
ioHelper,
}) : undefined;
const deployAndWatch = async () => {
latch = 'deploying';
await cloudWatchLogMonitor?.deactivate();
await this.invokeDeployFromWatch(options, cloudWatchLogMonitor);
// If latch is still 'deploying' after the 'await', that's fine,
// but if it's 'queued', that means we need to deploy again
while ((latch as 'deploying' | 'queued') === 'queued') {
// TypeScript doesn't realize latch can change between 'awaits',
// and thinks the above 'while' condition is always 'false' without the cast
latch = 'deploying';
await this.ioHost.asIoHelper().defaults.info("Detected file changes during deployment. Invoking 'cdk deploy' again");
await this.invokeDeployFromWatch(options, cloudWatchLogMonitor);
}
latch = 'open';
await cloudWatchLogMonitor?.activate();
};
chokidar
.watch(watchIncludes, {
ignored: watchExcludes,
cwd: rootDir,
})
.on('ready', async () => {
latch = 'open';
await this.ioHost.asIoHelper().defaults.debug("'watch' received the 'ready' event. From now on, all file changes will trigger a deployment");
await this.ioHost.asIoHelper().defaults.info("Triggering initial 'cdk deploy'");
await deployAndWatch();
})
.on('all', async (event: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', filePath?: string) => {
if (latch === 'pre-ready') {
await this.ioHost.asIoHelper().defaults.info(`'watch' is observing ${event === 'addDir' ? 'directory' : 'the file'} '%s' for changes`, filePath);
} else if (latch === 'open') {
await this.ioHost.asIoHelper().defaults.info("Detected change to '%s' (type: %s). Triggering 'cdk deploy'", filePath, event);
await deployAndWatch();
} else {
// this means latch is either 'deploying' or 'queued'
latch = 'queued';
await this.ioHost.asIoHelper().defaults.info(
"Detected change to '%s' (type: %s) while 'cdk deploy' is still running. " +
'Will queue for another deployment after this one finishes',
filePath,
event,
);
}
});
}
public async import(options: ImportOptions) {
const stacks = await this.selectStacksForDeploy(options.selector, true, true, false);
// set progress from options, this includes user and app config
if (options.progress) {
this.ioHost.stackProgress = options.progress;
}
if (stacks.stackCount > 1) {
throw new ToolkitError(
`Stack selection is ambiguous, please choose a specific stack for import [${stacks.stackArtifacts.map((x) => x.id).join(', ')}]`,
);
}
if (!process.stdout.isTTY && !options.resourceMappingFile) {
throw new ToolkitError('--resource-mapping is required when input is not a terminal');
}
const stack = stacks.stackArtifacts[0];
await this.ioHost.asIoHelper().defaults.info(chalk.bold(stack.displayName));
const resourceImporter = new ResourceImporter(stack, {
deployments: this.props.deployments,
ioHelper: asIoHelper(this.ioHost, 'import'),
});
const { additions, hasNonAdditions } = await resourceImporter.discoverImportableResources(options.force);
if (additions.length === 0) {
await this.ioHost.asIoHelper().defaults.warn(
'%s: no new resources compared to the currently deployed stack, skipping import.',
chalk.bold(stack.displayName),
);
return;
}
// Prepare a mapping of physical resources to CDK constructs
const actualImport = !options.resourceMappingFile
? await resourceImporter.askForResourceIdentifiers(additions)
: await resourceImporter.loadResourceIdentifiers(additions, options.resourceMappingFile);
if (actualImport.importResources.length === 0) {
await this.ioHost.asIoHelper().defaults.warn('No resources selected for import.');
return;
}
// If "--create-resource-mapping" option was passed, write the resource mapping to the given file and exit
if (options.recordResourceMapping) {
const outputFile = options.recordResourceMapping;
fs.ensureFileSync(outputFile);
await fs.writeJson(outputFile, actualImport.resourceMap, {
spaces: 2,
encoding: 'utf8',
});
await this.ioHost.asIoHelper().defaults.info('%s: mapping file written.', outputFile);
return;
}
// Import the resources according to the given mapping
await this.ioHost.asIoHelper().defaults.info('%s: importing resources into stack...', chalk.bold(stack.displayName));
const tags = tagsForStack(stack);
await resourceImporter.importResourcesFromMap(actualImport, {
roleArn: options.roleArn,
tags,
deploymentMethod: options.deploymentMethod,
usePreviousParameters: true,
rollback: options.rollback,
});
// Notify user of next steps
await this.ioHost.asIoHelper().defaults.info(
`Import operation complete. We recommend you run a ${chalk.blueBright('drift detection')} operation ` +
'to confirm your CDK app resource definitions are up-to-date. Read more here: ' +
chalk.underline.blueBright(
'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/detect-drift-stack.html',
),
);
if (actualImport.importResources.length < additions.length) {
await this.ioHost.asIoHelper().defaults.info('');
await this.ioHost.asIoHelper().defaults.warn(
`Some resources were skipped. Run another ${chalk.blueBright('cdk import')} or a ${chalk.blueBright('cdk deploy')} to bring the stack up-to-date with your CDK app definition.`,
);
} else if (hasNonAdditions) {
await this.ioHost.asIoHelper().defaults.info('');
await this.ioHost.asIoHelper().defaults.warn(
`Your app has pending updates or deletes excluded from this import operation. Run a ${chalk.blueBright('cdk deploy')} to bring the stack up-to-date with your CDK app definition.`,
);
}
}
public async destroy(options: DestroyOptions) {
const ioHelper = this.ioHost.asIoHelper();
// The stacks will have been ordered for deployment, so reverse them for deletion.
const stacks = (await this.selectStacksForDestroy(options.selector, options.exclusively)).reversed();
if (!options.force) {
const motivation = 'Destroying stacks is an irreversible action';
const question = `Are you sure you want to delete: ${chalk.blue(stacks.stackArtifacts.map((s) => s.hierarchicalId).join(', '))}`;
try {
await ioHelper.requestResponse(IO.CDK_TOOLKIT_I7010.req(question, { motivation }));
} catch (err: unknown) {
if (!ToolkitError.isToolkitError(err) || err.message != 'Aborted by user') {
throw err; // unexpected error
}
await ioHelper.notify(IO.CDK_TOOLKIT_E7010.msg(err.message));
return;
}
}
const action = options.fromDeploy ? 'deploy' : 'destroy';
for (const [index, stack] of stacks.stackArtifacts.entries()) {
await ioHelper.defaults.info(chalk.green('%s: destroying... [%s/%s]'), chalk.blue(stack.displayName), index + 1, stacks.stackCount);
try {
await this.props.deployments.destroyStack({
stack,
deployName: stack.stackName,
roleArn: options.roleArn,
});