-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathdeploy-stack.ts
More file actions
875 lines (774 loc) · 31.3 KB
/
deploy-stack.ts
File metadata and controls
875 lines (774 loc) · 31.3 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
import { format } from 'util';
import type * as cxapi from '@aws-cdk/cloud-assembly-api';
import type {
CreateChangeSetCommandInput,
CreateStackCommandInput,
DescribeChangeSetCommandOutput,
ExecuteChangeSetCommandInput,
UpdateStackCommandInput,
Tag,
} from '@aws-sdk/client-cloudformation';
import * as chalk from 'chalk';
import * as uuid from 'uuid';
import { AssetManifestBuilder } from './asset-manifest-builder';
import { publishAssets } from './asset-publishing';
import { addMetadataAssetsToManifest } from './assets';
import type {
ParameterValues,
ParameterChanges,
} from './cfn-api';
import {
changeSetHasNoChanges,
TemplateParameters,
waitForChangeSet,
waitForStackDeploy,
waitForStackDelete,
} from './cfn-api';
import { determineAllowCrossAccountAssetPublishing } from './checks';
import type { DeployStackResult, SuccessfulDeployStackResult } from './deployment-result';
import type { ChangeSetDeployment, DeploymentMethod, DirectDeployment } from '../../actions/deploy';
import { DeploymentError, DeploymentErrorCodes, ToolkitError } from '../../toolkit/toolkit-error';
import { formatErrorMessage } from '../../util';
import type { SDK, SdkProvider, ICloudFormationClient } from '../aws-auth/private';
import type { TemplateBodyParameter } from '../cloudformation';
import { makeBodyParameter, CfnEvaluationException, CloudFormationStack } from '../cloudformation';
import type { EnvironmentResources, StringWithoutPlaceholders } from '../environment';
import { EnvironmentResourcesRegistry } from '../environment';
import { HotswapPropertyOverrides, ICON, createHotswapPropertyOverrides } from '../hotswap/common';
import { tryHotswapDeployment } from '../hotswap/hotswap-deployments';
import type { IoHelper } from '../io/private';
import type { ResourcesToImport } from '../resource-import';
import { StackActivityMonitor } from '../stack-events';
import { EarlyValidationReporter } from './early-validation';
export interface DeployStackOptions {
/**
* The stack to be deployed
*/
readonly stack: cxapi.CloudFormationStackArtifact;
/**
* The environment to deploy this stack in
*
* The environment on the stack artifact may be unresolved, this one
* must be resolved.
*/
readonly resolvedEnvironment: cxapi.Environment;
/**
* The SDK to use for deploying the stack
*
* Should have been initialized with the correct role with which
* stack operations should be performed.
*/
readonly sdk: SDK;
/**
* SDK provider (seeded with default credentials)
*
* Will be used to:
*
* - Publish assets, either legacy assets or large CFN templates
* that aren't themselves assets from a manifest. (Needs an SDK
* Provider because the file publishing role is declared as part
* of the asset).
* - Hotswap
*/
readonly sdkProvider: SdkProvider;
/**
* Information about the bootstrap stack found in the target environment
*/
readonly envResources: EnvironmentResources;
/**
* Role to pass to CloudFormation to execute the change set
*
* To obtain a `StringWithoutPlaceholders`, run a regular
* string though `TargetEnvironment.replacePlaceholders`.
*
* @default - No execution role; CloudFormation either uses the role currently associated with
* the stack, or otherwise uses current AWS credentials
*/
readonly roleArn?: StringWithoutPlaceholders;
/**
* Notification ARNs to pass to CloudFormation to notify when the change set has completed
*
* @default - No notifications
*/
readonly notificationArns?: string[];
/**
* Name to deploy the stack under
*
* @default - Name from assembly
*/
readonly deployName?: string;
/**
* List of asset IDs which shouldn't be built
*
* @default - Build all assets
*/
readonly reuseAssets?: string[];
/**
* Tags to pass to CloudFormation to add to stack
*
* @default - No tags
*/
readonly tags?: Tag[];
/**
* What deployment method to use
*
* @default - Change set with defaults
*/
readonly deploymentMethod?: DeploymentMethod;
/**
* The collection of extra parameters
* (in addition to those used for assets)
* to pass to the deployed template.
* Note that parameters with `undefined` or empty values will be ignored,
* and not passed to the template.
*
* @default - No additional parameters will be passed to the template
*/
readonly parameters?: { [name: string]: string | undefined };
/**
* Use previous values for unspecified parameters
*
* If not set, all parameters must be specified for every deployment.
*
* @default false
*/
readonly usePreviousParameters?: boolean;
/**
* Deploy even if the deployed template is identical to the one we are about to deploy.
* @default false
*/
readonly forceDeployment?: boolean;
/**
* Rollback failed deployments
*
* @default true
*/
readonly rollback?: boolean;
/**
* The extra string to append to the User-Agent header when performing AWS SDK calls.
*
* @default - Nothing extra is appended to the User-Agent header
*/
readonly extraUserAgent?: string;
/**
* If set, change set of type IMPORT will be created, and resourcesToImport
* passed to it.
*/
readonly resourcesToImport?: ResourcesToImport;
/**
* If present, use this given template instead of the stored one
*
* @default - Use the stored template
*/
readonly overrideTemplate?: any;
/**
* Whether to build/publish assets in parallel
*
* @default true To remain backward compatible.
*/
readonly assetParallelism?: boolean;
}
export async function deployStack(options: DeployStackOptions, ioHelper: IoHelper): Promise<DeployStackResult> {
const stackArtifact = options.stack;
const stackEnv = options.resolvedEnvironment;
let deploymentMethod = options.deploymentMethod ?? { method: 'change-set' };
options.sdk.appendCustomUserAgent(options.extraUserAgent);
const cfn = options.sdk.cloudFormation();
const deployName = options.deployName || stackArtifact.stackName;
let cloudFormationStack = await CloudFormationStack.lookup(cfn, deployName);
if (cloudFormationStack.stackStatus.isCreationFailure) {
await ioHelper.defaults.debug(
`Found existing stack ${deployName} that had previously failed creation. Deleting it before attempting to re-create it.`,
);
await cfn.deleteStack({ StackName: deployName });
const deletedStack = await waitForStackDelete(cfn, ioHelper, deployName);
if (deletedStack && deletedStack.stackStatus.name !== 'DELETE_COMPLETE') {
throw new DeploymentError(
`Failed deleting stack ${deployName} that had previously failed creation (current state: ${deletedStack.stackStatus})`,
'FailedStackCleanupFailed',
);
}
// Update variable to mark that the stack does not exist anymore, but avoid
// doing an actual lookup in CloudFormation (which would be silly to do if
// we just deleted it).
cloudFormationStack = CloudFormationStack.doesNotExist(cfn, deployName);
}
// Detect "legacy" assets (which remain in the metadata) and publish them via
// an ad-hoc asset manifest, while passing their locations via template
// parameters.
const legacyAssets = new AssetManifestBuilder();
const assetParams = await addMetadataAssetsToManifest(
ioHelper,
stackArtifact,
legacyAssets,
options.envResources,
options.reuseAssets,
);
const finalParameterValues = { ...options.parameters, ...assetParams };
const templateParams = TemplateParameters.fromTemplate(stackArtifact.template);
const stackParams = options.usePreviousParameters
? templateParams.updateExisting(finalParameterValues, cloudFormationStack.parameters)
: templateParams.supplyAll(finalParameterValues);
if (await canSkipDeploy(options, cloudFormationStack, stackParams.hasChanges(cloudFormationStack.parameters), ioHelper)) {
await ioHelper.defaults.debug(`${deployName}: skipping deployment (use --force to override)`);
// if we can skip deployment and we are performing a hotswap, let the user know
// that no hotswap deployment happened
if (deploymentMethod?.method === 'hotswap') {
await ioHelper.defaults.info(
format(
`\n ${ICON} %s\n`,
chalk.bold('hotswap deployment skipped - no changes were detected (use --force to override)'),
),
);
}
return {
type: 'did-deploy-stack',
noOp: true,
outputs: cloudFormationStack.outputs,
stackArn: cloudFormationStack.stackId,
};
} else {
await ioHelper.defaults.debug(`${deployName}: deploying...`);
}
const bodyParameter = await makeBodyParameter(
ioHelper,
stackArtifact,
options.resolvedEnvironment,
legacyAssets,
options.envResources,
options.overrideTemplate,
);
let bootstrapStackName: string | undefined;
try {
bootstrapStackName = (await options.envResources.lookupToolkit()).stackName;
} catch (e) {
await ioHelper.defaults.debug(`Could not determine the bootstrap stack name: ${e}`);
}
await publishAssets(legacyAssets.toManifest(stackArtifact.assembly.directory), options.sdkProvider, stackEnv, {
parallel: options.assetParallelism,
allowCrossAccount: await determineAllowCrossAccountAssetPublishing(options.sdk, ioHelper, bootstrapStackName),
}, ioHelper);
// attempt to short-circuit the deployment if possible
if (deploymentMethod?.method === 'hotswap') {
try {
const hotswapModeNew = deploymentMethod?.fallback ? 'fall-back' : 'hotswap-only';
const hotswapPropertyOverrides = deploymentMethod.properties
? createHotswapPropertyOverrides(deploymentMethod.properties)
: new HotswapPropertyOverrides();
const hotswapDeploymentResult = await tryHotswapDeployment(
options.sdkProvider,
ioHelper,
stackParams.values,
cloudFormationStack,
stackArtifact,
hotswapModeNew,
hotswapPropertyOverrides,
);
if (hotswapDeploymentResult) {
return hotswapDeploymentResult;
}
await ioHelper.defaults.info(format(
'Could not perform a hotswap deployment, as the stack %s contains non-Asset changes',
stackArtifact.displayName,
));
} catch (e) {
if (!(e instanceof CfnEvaluationException)) {
throw e;
}
await ioHelper.defaults.info(format(
'Could not perform a hotswap deployment, because the CloudFormation template could not be resolved: %s',
formatErrorMessage(e),
));
}
if (deploymentMethod.fallback) {
await ioHelper.defaults.info('Falling back to doing a full deployment');
options.sdk.appendCustomUserAgent('cdk-hotswap/fallback');
deploymentMethod = deploymentMethod.fallback;
} else {
return {
type: 'did-deploy-stack',
noOp: true,
stackArn: cloudFormationStack.stackId,
outputs: cloudFormationStack.outputs,
};
}
}
// could not short-circuit the deployment, perform a full CFN deploy instead
const fullDeployment = new FullCloudFormationDeployment(
deploymentMethod,
options,
cloudFormationStack,
stackArtifact,
stackParams,
bodyParameter,
ioHelper,
);
return fullDeployment.performDeployment();
}
type CommonPrepareOptions = keyof CreateStackCommandInput &
keyof UpdateStackCommandInput &
keyof CreateChangeSetCommandInput;
type CommonExecuteOptions = keyof CreateStackCommandInput &
keyof UpdateStackCommandInput &
keyof ExecuteChangeSetCommandInput;
/**
* This class shares state and functionality between the different full deployment modes
*/
class FullCloudFormationDeployment {
private readonly cfn: ICloudFormationClient;
private readonly stackName: string;
private readonly update: boolean;
private readonly verb: string;
private readonly uuid: string;
constructor(
private readonly deploymentMethod: DirectDeployment | ChangeSetDeployment,
private readonly options: DeployStackOptions,
private readonly cloudFormationStack: CloudFormationStack,
private readonly stackArtifact: cxapi.CloudFormationStackArtifact,
private readonly stackParams: ParameterValues,
private readonly bodyParameter: TemplateBodyParameter,
private readonly ioHelper: IoHelper,
) {
this.cfn = options.sdk.cloudFormation();
this.stackName = options.deployName ?? stackArtifact.stackName;
this.update = cloudFormationStack.exists && cloudFormationStack.stackStatus.name !== 'REVIEW_IN_PROGRESS';
this.verb = this.update ? 'update' : 'create';
this.uuid = uuid.v4();
}
public async performDeployment(): Promise<DeployStackResult> {
const deploymentMethod = this.deploymentMethod ?? { method: 'change-set' };
if (deploymentMethod.method === 'direct' && this.options.resourcesToImport) {
throw new ToolkitError('ImportRequiresChangeSet', 'Importing resources requires a changeset deployment');
}
switch (deploymentMethod.method) {
case 'change-set':
return this.changeSetDeployment(deploymentMethod);
case 'direct':
return this.directDeployment();
}
}
private async changeSetDeployment(deploymentMethod: ChangeSetDeployment): Promise<DeployStackResult> {
const changeSetName = deploymentMethod.changeSetName ?? 'cdk-deploy-change-set';
const execute = deploymentMethod.execute ?? true;
const importExistingResources = deploymentMethod.importExistingResources ?? false;
const revertDrift = deploymentMethod.revertDrift ?? false;
const changeSetDescription = await this.createChangeSet(changeSetName, execute, importExistingResources, revertDrift);
await this.updateTerminationProtection();
if (changeSetHasNoChanges(changeSetDescription)) {
await this.ioHelper.defaults.debug(format('No changes are to be performed on %s.', this.stackName));
if (execute) {
await this.ioHelper.defaults.debug(format('Deleting empty change set %s', changeSetDescription.ChangeSetId));
await this.cfn.deleteChangeSet({
StackName: this.stackName,
ChangeSetName: changeSetName,
});
}
if (this.options.forceDeployment) {
await this.ioHelper.defaults.warn(
[
'You used the --force flag, but CloudFormation reported that the deployment would not make any changes.',
'According to CloudFormation, all resources are already up-to-date with the state in your CDK app.',
'',
'You cannot use the --force flag to get rid of changes you made in the console. Try using',
'CloudFormation drift detection instead: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html',
].join('\n'),
);
}
return {
type: 'did-deploy-stack',
noOp: true,
outputs: this.cloudFormationStack.outputs,
stackArn: changeSetDescription.StackId!,
};
}
if (!execute) {
await this.ioHelper.defaults.info(format(
'Changeset %s created and waiting in review for manual execution (--no-execute)',
changeSetDescription.ChangeSetId,
));
return {
type: 'did-deploy-stack',
noOp: false,
outputs: this.cloudFormationStack.outputs,
stackArn: changeSetDescription.StackId!,
};
}
// If there are replacements in the changeset, check the rollback flag and stack status
const replacement = hasReplacement(changeSetDescription);
const isPausedFailState = this.cloudFormationStack.stackStatus.isRollbackable;
const rollback = this.options.rollback ?? true;
if (isPausedFailState && replacement) {
return { type: 'failpaused-need-rollback-first', reason: 'replacement', status: this.cloudFormationStack.stackStatus.name };
}
if (isPausedFailState && rollback) {
return { type: 'failpaused-need-rollback-first', reason: 'not-norollback', status: this.cloudFormationStack.stackStatus.name };
}
if (!rollback && replacement) {
return { type: 'replacement-requires-rollback' };
}
return this.executeChangeSet(changeSetDescription);
}
private async createChangeSet(changeSetName: string, willExecute: boolean, importExistingResources: boolean, revertDrift: boolean) {
await this.cleanupOldChangeset(changeSetName);
await this.ioHelper.defaults.debug(`Attempting to create ChangeSet with name ${changeSetName} to ${this.verb} stack ${this.stackName}`);
await this.ioHelper.defaults.info(format('%s: creating CloudFormation changeset...', chalk.bold(this.stackName)));
const changeSet = await this.cfn.createChangeSet({
StackName: this.stackName,
ChangeSetName: changeSetName,
ChangeSetType: this.options.resourcesToImport ? 'IMPORT' : this.update ? 'UPDATE' : 'CREATE',
ResourcesToImport: this.options.resourcesToImport,
Description: `CDK Changeset for execution ${this.uuid}`,
ClientToken: `create${this.uuid}`,
ImportExistingResources: importExistingResources,
DeploymentMode: revertDrift ? 'REVERT_DRIFT' : undefined,
...this.commonPrepareOptions(),
});
await this.ioHelper.defaults.debug(format('Initiated creation of changeset: %s; waiting for it to finish creating...', changeSet.Id));
// Fetching all pages if we'll execute, so we can have the correct change count when monitoring.
const environmentResourcesRegistry = new EnvironmentResourcesRegistry();
const envResources = environmentResourcesRegistry.for(this.options.resolvedEnvironment, this.options.sdk, this.ioHelper);
const validationReporter = new EarlyValidationReporter(this.options.sdk, envResources);
try {
return await waitForChangeSet(this.cfn, this.ioHelper, this.stackName, changeSetName, {
fetchAll: willExecute,
validationReporter,
});
} catch (e: any) {
if (importExistingResources && ToolkitError.isDeploymentError(e) && e.deploymentErrorCode === 'ChangeSetCreationFailed') {
throw new DeploymentError(this.enhanceImportErrorMessage(e.message), 'ChangeSetCreationFailed');
}
throw e;
}
}
/**
* Enhance an import-related changeset error message by mapping CFN logical IDs to CDK construct paths.
*/
private enhanceImportErrorMessage(message: string): string {
// Only enhance the specific CFN error about importing existing resources
if (!message.includes('CloudFormation is attempting to import some resources because they already exist in your account')) {
return message;
}
const marker = 'The affected resources are ';
const markerIndex = message.indexOf(marker);
if (markerIndex === -1) {
return message;
}
// Only extract logical IDs from the "The affected resources are ..." suffix
const resourceList = message.substring(markerIndex + marker.length);
const logicalIdPattern = /\b([A-Za-z][A-Za-z0-9]+)\s+\(\{/g;
const resources = this.stackArtifact.template?.Resources ?? {};
const affected: string[] = [];
for (const match of resourceList.matchAll(logicalIdPattern)) {
const logicalId = match[1];
const path = resources[logicalId]?.Metadata?.['aws:cdk:path'];
affected.push(path ? ` - ${path} (${logicalId})` : ` - ${logicalId}`);
}
return [
`Import of existing resources failed for stack '${this.stackName}' because the following resources need a DeletionPolicy of 'Retain' or 'RetainExceptOnCreate':`,
...affected,
'',
"Set the removal policy to 'RemovalPolicy.RETAIN' or 'RemovalPolicy.RETAIN_ON_UPDATE_OR_DELETE' on these resources.",
'See https://docs.aws.amazon.com/cdk/v2/guide/resources.html#resources-removal',
].join('\n');
}
private async executeChangeSet(changeSet: DescribeChangeSetCommandOutput): Promise<SuccessfulDeployStackResult> {
await this.ioHelper.defaults.debug(format('Initiating execution of changeset %s on stack %s', changeSet.ChangeSetId, this.stackName));
await this.cfn.executeChangeSet({
StackName: this.stackName,
ChangeSetName: changeSet.ChangeSetName!,
ClientRequestToken: `exec${this.uuid}`,
...this.commonExecuteOptions(),
});
await this.ioHelper.defaults.debug(
format(
'Execution of changeset %s on stack %s has started; waiting for the update to complete...',
changeSet.ChangeSetId,
this.stackName,
),
);
// +1 for the extra event emitted from updates.
const changeSetLength: number = (changeSet.Changes ?? []).length + (this.update ? 1 : 0);
return this.monitorDeployment(changeSet.CreationTime!, changeSetLength);
}
private async cleanupOldChangeset(changeSetName: string) {
if (this.cloudFormationStack.exists) {
// Delete any existing change sets generated by CDK since change set names must be unique.
// The delete request is successful as long as the stack exists (even if the change set does not exist).
await this.ioHelper.defaults.debug(`Removing existing change set with name ${changeSetName} if it exists`);
await this.cfn.deleteChangeSet({
StackName: this.stackName,
ChangeSetName: changeSetName,
});
}
}
private async updateTerminationProtection() {
// Update termination protection only if it has changed.
const terminationProtection = this.stackArtifact.terminationProtection ?? false;
if (!!this.cloudFormationStack.terminationProtection !== terminationProtection) {
await this.ioHelper.defaults.debug(
format (
'Updating termination protection from %s to %s for stack %s',
this.cloudFormationStack.terminationProtection,
terminationProtection,
this.stackName,
),
);
await this.cfn.updateTerminationProtection({
StackName: this.stackName,
EnableTerminationProtection: terminationProtection,
});
await this.ioHelper.defaults.debug(format('Termination protection updated to %s for stack %s', terminationProtection, this.stackName));
}
}
private async directDeployment(): Promise<SuccessfulDeployStackResult> {
await this.ioHelper.defaults.info(format('%s: %s stack...', chalk.bold(this.stackName), this.update ? 'updating' : 'creating'));
const startTime = new Date();
if (this.update) {
await this.updateTerminationProtection();
try {
await this.cfn.updateStack({
StackName: this.stackName,
ClientRequestToken: `update${this.uuid}`,
...this.commonPrepareOptions(),
...this.commonExecuteOptions(),
});
} catch (err: any) {
if (err.message === 'No updates are to be performed.') {
await this.ioHelper.defaults.debug(format('No updates are to be performed for stack %s', this.stackName));
return {
type: 'did-deploy-stack',
noOp: true,
outputs: this.cloudFormationStack.outputs,
stackArn: this.cloudFormationStack.stackId,
};
}
throw err;
}
return this.monitorDeployment(startTime, undefined);
} else {
// Take advantage of the fact that we can set termination protection during create
const terminationProtection = this.stackArtifact.terminationProtection ?? false;
await this.cfn.createStack({
StackName: this.stackName,
ClientRequestToken: `create${this.uuid}`,
...(terminationProtection ? { EnableTerminationProtection: true } : undefined),
...this.commonPrepareOptions(),
...this.commonExecuteOptions(),
});
return this.monitorDeployment(startTime, undefined);
}
}
private async monitorDeployment(startTime: Date, expectedChanges: number | undefined): Promise<SuccessfulDeployStackResult> {
const monitor = new StackActivityMonitor({
cfn: this.cfn,
stack: this.stackArtifact,
stackName: this.stackName,
resourcesTotal: expectedChanges,
ioHelper: this.ioHelper,
changeSetCreationTime: startTime,
envResources: this.options.envResources,
});
await monitor.start();
let finalState = this.cloudFormationStack;
try {
const successStack = await waitForStackDeploy(this.cfn, this.ioHelper, this.stackName);
// This shouldn't really happen, but catch it anyway. You never know.
if (!successStack) {
throw new DeploymentError('Stack deploy failed (the stack disappeared while we were deploying it)', DeploymentErrorCodes.STACK_DISAPPEARED_ERROR_CODE);
}
finalState = successStack;
} catch (e: any) {
throw new DeploymentError(suffixWithErrors(formatErrorMessage(e), monitor.allErrorMessages), monitor.rootCauseErrorCode ?? 'StackDeployFailed');
} finally {
await monitor.stop();
}
await this.ioHelper.defaults.debug(format('Stack %s has completed updating', this.stackName));
return {
type: 'did-deploy-stack',
noOp: false,
outputs: finalState.outputs,
stackArn: finalState.stackId,
};
}
/**
* Return the options that are shared between CreateStack, UpdateStack and CreateChangeSet
*/
private commonPrepareOptions(): Partial<Pick<UpdateStackCommandInput, CommonPrepareOptions>> {
return {
Capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM', 'CAPABILITY_AUTO_EXPAND'],
NotificationARNs: this.options.notificationArns,
Parameters: this.stackParams.apiParameters,
RoleARN: this.options.roleArn,
TemplateBody: this.bodyParameter.TemplateBody,
TemplateURL: this.bodyParameter.TemplateURL,
Tags: this.options.tags,
};
}
/**
* Return the options that are shared between UpdateStack and CreateChangeSet
*
* Be careful not to add in keys for options that aren't used, as the features may not have been
* deployed everywhere yet.
*/
private commonExecuteOptions(): Partial<Pick<UpdateStackCommandInput, CommonExecuteOptions>> {
const shouldDisableRollback = this.options.rollback === false;
return {
StackName: this.stackName,
...(shouldDisableRollback ? { DisableRollback: true } : undefined),
};
}
}
export interface DestroyStackOptions {
/**
* The stack to be destroyed
*/
stack: cxapi.CloudFormationStackArtifact;
sdk: SDK;
roleArn?: string;
deployName?: string;
}
export interface DestroyStackResult {
/**
* The ARN of the stack that was destroyed, if any.
*
* If the stack didn't exist to begin with, the operation will succeed
* but this value will be undefined.
*/
readonly stackArn?: string;
}
export async function destroyStack(options: DestroyStackOptions, ioHelper: IoHelper): Promise<DestroyStackResult> {
const deployName = options.deployName || options.stack.stackName;
const cfn = options.sdk.cloudFormation();
const currentStack = await CloudFormationStack.lookup(cfn, deployName);
if (!currentStack.exists) {
return {};
}
const monitor = new StackActivityMonitor({
cfn,
stack: options.stack,
stackName: deployName,
ioHelper: ioHelper,
});
await monitor.start();
try {
await cfn.deleteStack({ StackName: deployName, RoleARN: options.roleArn });
const destroyedStack = await waitForStackDelete(cfn, ioHelper, deployName);
if (destroyedStack && destroyedStack.stackStatus.name !== 'DELETE_COMPLETE') {
throw new DeploymentError(`Failed to destroy ${deployName}: ${destroyedStack.stackStatus}`, 'StackDestroyFailed');
}
return { stackArn: currentStack.stackId };
} catch (e: any) {
throw new DeploymentError(suffixWithErrors(formatErrorMessage(e), monitor.allErrorMessages), monitor.rootCauseErrorCode ?? 'StackDestroyFailed');
} finally {
if (monitor) {
await monitor.stop();
}
}
}
/**
* Checks whether we can skip deployment
*
* We do this in a complicated way by preprocessing (instead of just
* looking at the changeset), because if there are nested stacks involved
* the changeset will always show the nested stacks as needing to be
* updated, and the deployment will take a long time to in effect not
* do anything.
*/
async function canSkipDeploy(
deployStackOptions: DeployStackOptions,
cloudFormationStack: CloudFormationStack,
parameterChanges: ParameterChanges,
ioHelper: IoHelper,
): Promise<boolean> {
const deployName = deployStackOptions.deployName || deployStackOptions.stack.stackName;
await ioHelper.defaults.debug(`${deployName}: checking if we can skip deploy`);
// Forced deploy
if (deployStackOptions.forceDeployment) {
await ioHelper.defaults.debug(`${deployName}: forced deployment`);
return false;
}
// Creating changeset only (default true), never skip
if (
deployStackOptions.deploymentMethod?.method === 'change-set' &&
deployStackOptions.deploymentMethod.execute === false
) {
await ioHelper.defaults.debug(`${deployName}: --no-execute, always creating change set`);
return false;
}
// Drift-aware
if (
deployStackOptions.deploymentMethod?.method === 'change-set' &&
deployStackOptions.deploymentMethod.revertDrift
) {
await ioHelper.defaults.debug(`${deployName}: --revert-drift, always creating change set`);
return false;
}
// No existing stack
if (!cloudFormationStack.exists) {
await ioHelper.defaults.debug(`${deployName}: no existing stack`);
return false;
}
// Template has changed (assets taken into account here)
if (JSON.stringify(deployStackOptions.stack.template) !== JSON.stringify(await cloudFormationStack.template())) {
await ioHelper.defaults.debug(`${deployName}: template has changed`);
return false;
}
// Tags have changed
if (!compareTags(cloudFormationStack.tags, deployStackOptions.tags ?? [])) {
await ioHelper.defaults.debug(`${deployName}: tags have changed`);
return false;
}
// Notification arns have changed
if (!arrayEquals(cloudFormationStack.notificationArns, deployStackOptions.notificationArns ?? [])) {
await ioHelper.defaults.debug(`${deployName}: notification arns have changed`);
return false;
}
// Termination protection has been updated
if (!!deployStackOptions.stack.terminationProtection !== !!cloudFormationStack.terminationProtection) {
await ioHelper.defaults.debug(`${deployName}: termination protection has been updated`);
return false;
}
// Parameters have changed
if (parameterChanges) {
if (parameterChanges === 'ssm') {
await ioHelper.defaults.debug(`${deployName}: some parameters come from SSM so we have to assume they may have changed`);
} else {
await ioHelper.defaults.debug(`${deployName}: parameters have changed`);
}
return false;
}
// Existing stack is in a failed state
if (cloudFormationStack.stackStatus.isFailure) {
await ioHelper.defaults.debug(`${deployName}: stack is in a failure state`);
return false;
}
// We can skip deploy
return true;
}
/**
* Compares two list of tags, returns true if identical.
*/
function compareTags(a: Tag[], b: Tag[]): boolean {
if (a.length !== b.length) {
return false;
}
for (const aTag of a) {
const bTag = b.find((tag) => tag.Key === aTag.Key);
if (!bTag || bTag.Value !== aTag.Value) {
return false;
}
}
return true;
}
function suffixWithErrors(msg: string, errors?: string[]) {
return errors && errors.length > 0 ? `${msg}: ${errors.join(', ')}` : msg;
}
function arrayEquals(a: any[], b: any[]): boolean {
return a.every((item) => b.includes(item)) && b.every((item) => a.includes(item));
}
function hasReplacement(cs: DescribeChangeSetCommandOutput) {
return (cs.Changes ?? []).some(c => {
const a = c.ResourceChange?.PolicyAction;
return a === 'ReplaceAndDelete' || a === 'ReplaceAndRetain' || a === 'ReplaceAndSnapshot';
});
}