@intelligems/sst 2.47.3 → 2.49.3-ig.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,516 +0,0 @@
1
- import * as uuid from "uuid";
2
- import { addMetadataAssetsToManifest } from "sst-aws-cdk/lib/assets.js";
3
- import { debug, print, warning } from "sst-aws-cdk/lib/logging.js";
4
- import { CfnEvaluationException } from "sst-aws-cdk/lib/api/evaluate-cloudformation-template.js";
5
- import { HotswapMode, HotswapPropertyOverrides, } from "sst-aws-cdk/lib/api/hotswap/common.js";
6
- import { tryHotswapDeployment } from "sst-aws-cdk/lib/api/hotswap-deployments.js";
7
- import { changeSetHasNoChanges, CloudFormationStack, TemplateParameters, waitForChangeSet, waitForStackDeploy, waitForStackDelete, } from "sst-aws-cdk/lib/api/util/cloudformation.js";
8
- import { makeBodyParameter, } from "sst-aws-cdk/lib/api/util/template-body-parameter.js";
9
- import { AssetManifestBuilder } from "sst-aws-cdk/lib/util/asset-manifest-builder.js";
10
- import { determineAllowCrossAccountAssetPublishing } from "sst-aws-cdk/lib/api/util/checks.js";
11
- import { publishAssets } from "sst-aws-cdk/lib/util/asset-publishing.js";
12
- import { callWithRetry } from "./util.js";
13
- export function assertIsSuccessfulDeployStackResult(x) {
14
- if (x.type !== "did-deploy-stack") {
15
- throw new Error(`Unexpected deployStack result. This should not happen: ${JSON.stringify(x)}. If you are seeing this error, please report it at https://github.com/aws/aws-cdk/issues/new/choose.`);
16
- }
17
- }
18
- export async function deployStack(options) {
19
- const stackArtifact = options.stack;
20
- const stackEnv = options.resolvedEnvironment;
21
- options.sdk.appendCustomUserAgent(options.extraUserAgent);
22
- const cfn = options.sdk.cloudFormation();
23
- const deployName = options.deployName || stackArtifact.stackName;
24
- let cloudFormationStack = await callWithRetry(() => CloudFormationStack.lookup(cfn, deployName));
25
- if (cloudFormationStack.stackStatus.isCreationFailure) {
26
- debug(`Found existing stack ${deployName} that had previously failed creation. Deleting it before attempting to re-create it.`);
27
- await cfn.deleteStack({ StackName: deployName });
28
- const deletedStack = await waitForStackDelete(cfn, deployName);
29
- if (deletedStack && deletedStack.stackStatus.name !== "DELETE_COMPLETE") {
30
- throw new Error(`Failed deleting stack ${deployName} that had previously failed creation (current state: ${deletedStack.stackStatus})`);
31
- }
32
- // Update variable to mark that the stack does not exist anymore, but avoid
33
- // doing an actual lookup in CloudFormation (which would be silly to do if
34
- // we just deleted it).
35
- cloudFormationStack = CloudFormationStack.doesNotExist(cfn, deployName);
36
- }
37
- // Detect "legacy" assets (which remain in the metadata) and publish them via
38
- // an ad-hoc asset manifest, while passing their locations via template
39
- // parameters.
40
- const legacyAssets = new AssetManifestBuilder();
41
- const assetParams = await addMetadataAssetsToManifest(stackArtifact, legacyAssets, options.envResources, options.reuseAssets);
42
- const finalParameterValues = { ...options.parameters, ...assetParams };
43
- const templateParams = TemplateParameters.fromTemplate(stackArtifact.template);
44
- const stackParams = options.usePreviousParameters
45
- ? templateParams.updateExisting(finalParameterValues, cloudFormationStack.parameters)
46
- : templateParams.supplyAll(finalParameterValues);
47
- if (await canSkipDeploy(options, cloudFormationStack, stackParams.hasChanges(cloudFormationStack.parameters))) {
48
- debug(`${deployName}: skipping deployment (use --force to override)`);
49
- // if we can skip deployment and we are performing a hotswap, let the user know
50
- // that no hotswap deployment happened
51
- if (options.hotswap) {
52
- }
53
- return {
54
- type: "did-deploy-stack",
55
- noOp: true,
56
- outputs: cloudFormationStack.outputs,
57
- stackArn: cloudFormationStack.stackId,
58
- };
59
- }
60
- else {
61
- debug(`${deployName}: deploying...`);
62
- }
63
- const bodyParameter = await makeBodyParameter(stackArtifact, options.resolvedEnvironment, legacyAssets, options.envResources, options.overrideTemplate);
64
- let bootstrapStackName;
65
- try {
66
- bootstrapStackName = (await options.envResources.lookupToolkit()).stackName;
67
- }
68
- catch (e) {
69
- debug(`Could not determine the bootstrap stack name: ${e}`);
70
- }
71
- await publishAssets(legacyAssets.toManifest(stackArtifact.assembly.directory), options.sdkProvider, stackEnv, {
72
- parallel: options.assetParallelism,
73
- allowCrossAccount: await determineAllowCrossAccountAssetPublishing(options.sdk, bootstrapStackName),
74
- });
75
- const hotswapMode = options.hotswap;
76
- const hotswapPropertyOverrides = options.hotswapPropertyOverrides ?? new HotswapPropertyOverrides();
77
- if (hotswapMode && hotswapMode !== HotswapMode.FULL_DEPLOYMENT) {
78
- // attempt to short-circuit the deployment if possible
79
- try {
80
- const hotswapDeploymentResult = await tryHotswapDeployment(options.sdkProvider, stackParams.values, cloudFormationStack, stackArtifact, hotswapMode, hotswapPropertyOverrides);
81
- if (hotswapDeploymentResult) {
82
- return hotswapDeploymentResult;
83
- }
84
- print("Could not perform a hotswap deployment, as the stack %s contains non-Asset changes", stackArtifact.displayName);
85
- }
86
- catch (e) {
87
- if (!(e instanceof CfnEvaluationException)) {
88
- throw e;
89
- }
90
- print("Could not perform a hotswap deployment, because the CloudFormation template could not be resolved: %s", e.message);
91
- }
92
- if (hotswapMode === HotswapMode.FALL_BACK) {
93
- print("Falling back to doing a full deployment");
94
- options.sdk.appendCustomUserAgent("cdk-hotswap/fallback");
95
- }
96
- else {
97
- return {
98
- type: "did-deploy-stack",
99
- noOp: true,
100
- stackArn: cloudFormationStack.stackId,
101
- outputs: cloudFormationStack.outputs,
102
- };
103
- }
104
- }
105
- // could not short-circuit the deployment, perform a full CFN deploy instead
106
- const fullDeployment = new FullCloudFormationDeployment(options, cloudFormationStack, stackArtifact, stackParams, bodyParameter);
107
- return fullDeployment.performDeployment();
108
- }
109
- /**
110
- * This class shares state and functionality between the different full deployment modes
111
- */
112
- class FullCloudFormationDeployment {
113
- options;
114
- cloudFormationStack;
115
- stackArtifact;
116
- stackParams;
117
- bodyParameter;
118
- cfn;
119
- stackName;
120
- update;
121
- verb;
122
- uuid;
123
- constructor(options, cloudFormationStack, stackArtifact, stackParams, bodyParameter) {
124
- this.options = options;
125
- this.cloudFormationStack = cloudFormationStack;
126
- this.stackArtifact = stackArtifact;
127
- this.stackParams = stackParams;
128
- this.bodyParameter = bodyParameter;
129
- this.cfn = options.sdk.cloudFormation();
130
- this.stackName = options.deployName ?? stackArtifact.stackName;
131
- this.update =
132
- cloudFormationStack.exists &&
133
- cloudFormationStack.stackStatus.name !== "REVIEW_IN_PROGRESS";
134
- this.verb = this.update ? "update" : "create";
135
- this.uuid = uuid.v4();
136
- }
137
- async performDeployment() {
138
- const deploymentMethod = this.options.deploymentMethod ?? {
139
- method: "change-set",
140
- };
141
- if (deploymentMethod.method === "direct" &&
142
- this.options.resourcesToImport) {
143
- throw new Error("Importing resources requires a changeset deployment");
144
- }
145
- switch (deploymentMethod.method) {
146
- case "change-set":
147
- return this.changeSetDeployment(deploymentMethod);
148
- case "direct":
149
- return this.directDeployment();
150
- }
151
- }
152
- async changeSetDeployment(deploymentMethod) {
153
- const changeSetName = deploymentMethod.changeSetName ?? "cdk-deploy-change-set";
154
- const execute = deploymentMethod.execute ?? true;
155
- const changeSetDescription = await this.createChangeSet(changeSetName, execute);
156
- await this.updateTerminationProtection();
157
- if (changeSetHasNoChanges(changeSetDescription)) {
158
- debug("No changes are to be performed on %s.", this.stackName);
159
- if (execute) {
160
- debug("Deleting empty change set %s", changeSetDescription.ChangeSetId);
161
- await this.cfn.deleteChangeSet({
162
- StackName: this.stackName,
163
- ChangeSetName: changeSetName,
164
- });
165
- }
166
- if (this.options.force) {
167
- warning([
168
- "You used the --force flag, but CloudFormation reported that the deployment would not make any changes.",
169
- "According to CloudFormation, all resources are already up-to-date with the state in your CDK app.",
170
- "",
171
- "You cannot use the --force flag to get rid of changes you made in the console. Try using",
172
- "CloudFormation drift detection instead: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html",
173
- ].join("\n"));
174
- }
175
- return {
176
- type: "did-deploy-stack",
177
- noOp: true,
178
- outputs: this.cloudFormationStack.outputs,
179
- stackArn: changeSetDescription.StackId,
180
- };
181
- }
182
- if (!execute) {
183
- print("Changeset %s created and waiting in review for manual execution (--no-execute)", changeSetDescription.ChangeSetId);
184
- return {
185
- type: "did-deploy-stack",
186
- noOp: false,
187
- outputs: this.cloudFormationStack.outputs,
188
- stackArn: changeSetDescription.StackId,
189
- };
190
- }
191
- // If there are replacements in the changeset, check the rollback flag and stack status
192
- const replacement = hasReplacement(changeSetDescription);
193
- const isPausedFailState = this.cloudFormationStack.stackStatus.isRollbackable;
194
- const rollback = this.options.rollback ?? true;
195
- if (isPausedFailState && replacement) {
196
- return { type: "failpaused-need-rollback-first", reason: "replacement" };
197
- }
198
- if (isPausedFailState && !rollback) {
199
- return {
200
- type: "failpaused-need-rollback-first",
201
- reason: "not-norollback",
202
- };
203
- }
204
- if (!rollback && replacement) {
205
- return { type: "replacement-requires-norollback" };
206
- }
207
- return this.executeChangeSet(changeSetDescription);
208
- }
209
- async createChangeSet(changeSetName, willExecute) {
210
- await this.cleanupOldChangeset(changeSetName);
211
- debug(`Attempting to create ChangeSet with name ${changeSetName} to ${this.verb} stack ${this.stackName}`);
212
- const changeSet = await this.cfn.createChangeSet({
213
- StackName: this.stackName,
214
- ChangeSetName: changeSetName,
215
- ChangeSetType: this.options.resourcesToImport
216
- ? "IMPORT"
217
- : this.update
218
- ? "UPDATE"
219
- : "CREATE",
220
- ResourcesToImport: this.options.resourcesToImport,
221
- Description: `CDK Changeset for execution ${this.uuid}`,
222
- ClientToken: `create${this.uuid}`,
223
- ...this.commonPrepareOptions(),
224
- });
225
- debug("Initiated creation of changeset: %s; waiting for it to finish creating...", changeSet.Id);
226
- // Fetching all pages if we'll execute, so we can have the correct change count when monitoring.
227
- return waitForChangeSet(this.cfn, this.stackName, changeSetName, {
228
- fetchAll: willExecute,
229
- });
230
- }
231
- async executeChangeSet(changeSet) {
232
- debug("Initiating execution of changeset %s on stack %s", changeSet.ChangeSetId, this.stackName);
233
- await this.cfn.executeChangeSet({
234
- StackName: this.stackName,
235
- ChangeSetName: changeSet.ChangeSetName,
236
- ClientRequestToken: `exec${this.uuid}`,
237
- ...this.commonExecuteOptions(),
238
- });
239
- debug("Execution of changeset %s on stack %s has started; waiting for the update to complete...", changeSet.ChangeSetId, this.stackName);
240
- // +1 for the extra event emitted from updates.
241
- const changeSetLength = (changeSet.Changes ?? []).length + (this.update ? 1 : 0);
242
- return this.monitorDeployment(changeSet.CreationTime, changeSetLength);
243
- }
244
- async cleanupOldChangeset(changeSetName) {
245
- if (this.cloudFormationStack.exists) {
246
- // Delete any existing change sets generated by CDK since change set names must be unique.
247
- // The delete request is successful as long as the stack exists (even if the change set does not exist).
248
- debug(`Removing existing change set with name ${changeSetName} if it exists`);
249
- await this.cfn.deleteChangeSet({
250
- StackName: this.stackName,
251
- ChangeSetName: changeSetName,
252
- });
253
- }
254
- }
255
- async updateTerminationProtection() {
256
- // Update termination protection only if it has changed.
257
- const terminationProtection = this.stackArtifact.terminationProtection ?? false;
258
- if (!!this.cloudFormationStack.terminationProtection !== terminationProtection) {
259
- debug("Updating termination protection from %s to %s for stack %s", this.cloudFormationStack.terminationProtection, terminationProtection, this.stackName);
260
- await this.cfn.updateTerminationProtection({
261
- StackName: this.stackName,
262
- EnableTerminationProtection: terminationProtection,
263
- });
264
- debug("Termination protection updated to %s for stack %s", terminationProtection, this.stackName);
265
- }
266
- }
267
- async directDeployment() {
268
- const startTime = new Date();
269
- if (this.update) {
270
- await this.updateTerminationProtection();
271
- try {
272
- await this.cfn.updateStack({
273
- StackName: this.stackName,
274
- ClientRequestToken: `update${this.uuid}`,
275
- ...this.commonPrepareOptions(),
276
- ...this.commonExecuteOptions(),
277
- });
278
- }
279
- catch (err) {
280
- if (err.message === "No updates are to be performed.") {
281
- debug("No updates are to be performed for stack %s", this.stackName);
282
- return {
283
- type: "did-deploy-stack",
284
- noOp: true,
285
- outputs: this.cloudFormationStack.outputs,
286
- stackArn: this.cloudFormationStack.stackId,
287
- };
288
- }
289
- throw err;
290
- }
291
- if (this.options.noMonitor)
292
- return;
293
- return this.monitorDeployment(startTime, undefined);
294
- }
295
- else {
296
- // Take advantage of the fact that we can set termination protection during create
297
- const terminationProtection = this.stackArtifact.terminationProtection ?? false;
298
- await this.cfn.createStack({
299
- StackName: this.stackName,
300
- ClientRequestToken: `create${this.uuid}`,
301
- ...(terminationProtection
302
- ? { EnableTerminationProtection: true }
303
- : undefined),
304
- ...this.commonPrepareOptions(),
305
- ...this.commonExecuteOptions(),
306
- });
307
- if (this.options.noMonitor)
308
- return;
309
- return this.monitorDeployment(startTime, undefined);
310
- }
311
- }
312
- async monitorDeployment(startTime, expectedChanges) {
313
- // const monitor = this.options.quiet
314
- // ? undefined
315
- // : StackActivityMonitor.withDefaultPrinter(
316
- // this.cfn,
317
- // this.stackName,
318
- // this.stackArtifact,
319
- // {
320
- // resourcesTotal: expectedChanges,
321
- // progress: this.options.progress,
322
- // changeSetCreationTime: startTime,
323
- // ci: this.options.ci,
324
- // }
325
- // ).start();
326
- let finalState = this.cloudFormationStack;
327
- try {
328
- const successStack = await waitForStackDeploy(this.cfn, this.stackName);
329
- // This shouldn't really happen, but catch it anyway. You never know.
330
- if (!successStack) {
331
- throw new Error("Stack deploy failed (the stack disappeared while we were deploying it)");
332
- }
333
- finalState = successStack;
334
- }
335
- catch (e) {
336
- throw new Error(suffixWithErrors(e.message /*, monitor?.errors*/));
337
- }
338
- finally {
339
- // await monitor?.stop();
340
- }
341
- debug("Stack %s has completed updating", this.stackName);
342
- return {
343
- type: "did-deploy-stack",
344
- noOp: false,
345
- outputs: finalState.outputs,
346
- stackArn: finalState.stackId,
347
- };
348
- }
349
- /**
350
- * Return the options that are shared between CreateStack, UpdateStack and CreateChangeSet
351
- */
352
- commonPrepareOptions() {
353
- return {
354
- Capabilities: [
355
- "CAPABILITY_IAM",
356
- "CAPABILITY_NAMED_IAM",
357
- "CAPABILITY_AUTO_EXPAND",
358
- ],
359
- NotificationARNs: this.options.notificationArns,
360
- Parameters: this.stackParams.apiParameters,
361
- RoleARN: this.options.roleArn,
362
- TemplateBody: this.bodyParameter.TemplateBody,
363
- TemplateURL: this.bodyParameter.TemplateURL,
364
- Tags: this.options.tags,
365
- };
366
- }
367
- /**
368
- * Return the options that are shared between UpdateStack and CreateChangeSet
369
- *
370
- * Be careful not to add in keys for options that aren't used, as the features may not have been
371
- * deployed everywhere yet.
372
- */
373
- commonExecuteOptions() {
374
- const shouldDisableRollback = this.options.rollback === false;
375
- return {
376
- StackName: this.stackName,
377
- ...(shouldDisableRollback ? { DisableRollback: true } : undefined),
378
- };
379
- }
380
- }
381
- export async function destroyStack(options) {
382
- const deployName = options.deployName || options.stack.stackName;
383
- const cfn = options.sdk.cloudFormation();
384
- const currentStack = await CloudFormationStack.lookup(cfn, deployName);
385
- if (!currentStack.exists) {
386
- return;
387
- }
388
- /*
389
- const monitor = options.quiet
390
- ? undefined
391
- : StackActivityMonitor.withDefaultPrinter(cfn, deployName, options.stack, {
392
- ci: options.ci,
393
- }).start();
394
- */
395
- try {
396
- await cfn.deleteStack({ StackName: deployName, RoleARN: options.roleArn });
397
- const destroyedStack = await waitForStackDelete(cfn, deployName);
398
- if (destroyedStack &&
399
- destroyedStack.stackStatus.name !== "DELETE_COMPLETE") {
400
- throw new Error(`Failed to destroy ${deployName}: ${destroyedStack.stackStatus}`);
401
- }
402
- }
403
- catch (e) {
404
- throw new Error(suffixWithErrors(e.message /* , monitor?.errors */));
405
- }
406
- finally {
407
- /*
408
- if (monitor) {
409
- await monitor.stop();
410
- }
411
- */
412
- }
413
- }
414
- /**
415
- * Checks whether we can skip deployment
416
- *
417
- * We do this in a complicated way by preprocessing (instead of just
418
- * looking at the changeset), because if there are nested stacks involved
419
- * the changeset will always show the nested stacks as needing to be
420
- * updated, and the deployment will take a long time to in effect not
421
- * do anything.
422
- */
423
- async function canSkipDeploy(deployStackOptions, cloudFormationStack, parameterChanges) {
424
- const deployName = deployStackOptions.deployName || deployStackOptions.stack.stackName;
425
- debug(`${deployName}: checking if we can skip deploy`);
426
- // Forced deploy
427
- if (deployStackOptions.force) {
428
- debug(`${deployName}: forced deployment`);
429
- return false;
430
- }
431
- // Creating changeset only (default true), never skip
432
- if (deployStackOptions.deploymentMethod?.method === "change-set" &&
433
- deployStackOptions.deploymentMethod.execute === false) {
434
- debug(`${deployName}: --no-execute, always creating change set`);
435
- return false;
436
- }
437
- // No existing stack
438
- if (!cloudFormationStack.exists) {
439
- debug(`${deployName}: no existing stack`);
440
- return false;
441
- }
442
- // SST check: stack is not busy
443
- if (cloudFormationStack.stackStatus.isInProgress) {
444
- debug(`${deployName}: stack is busy`);
445
- return false;
446
- }
447
- // Template has changed (assets taken into account here)
448
- if (JSON.stringify(deployStackOptions.stack.template) !==
449
- JSON.stringify(await cloudFormationStack.template())) {
450
- debug(`${deployName}: template has changed`);
451
- return false;
452
- }
453
- // Tags have changed
454
- if (!compareTags(cloudFormationStack.tags, deployStackOptions.tags ?? [])) {
455
- debug(`${deployName}: tags have changed`);
456
- return false;
457
- }
458
- // Notification arns have changed
459
- if (!arrayEquals(cloudFormationStack.notificationArns, deployStackOptions.notificationArns ?? [])) {
460
- debug(`${deployName}: notification arns have changed`);
461
- return false;
462
- }
463
- // Termination protection has been updated
464
- if (!!deployStackOptions.stack.terminationProtection !==
465
- !!cloudFormationStack.terminationProtection) {
466
- debug(`${deployName}: termination protection has been updated`);
467
- return false;
468
- }
469
- // Parameters have changed
470
- if (parameterChanges) {
471
- if (parameterChanges === "ssm") {
472
- debug(`${deployName}: some parameters come from SSM so we have to assume they may have changed`);
473
- }
474
- else {
475
- debug(`${deployName}: parameters have changed`);
476
- }
477
- return false;
478
- }
479
- // Existing stack is in a failed state
480
- if (cloudFormationStack.stackStatus.isFailure) {
481
- debug(`${deployName}: stack is in a failure state`);
482
- return false;
483
- }
484
- // We can skip deploy
485
- return true;
486
- }
487
- /**
488
- * Compares two list of tags, returns true if identical.
489
- */
490
- function compareTags(a, b) {
491
- if (a.length !== b.length) {
492
- return false;
493
- }
494
- for (const aTag of a) {
495
- const bTag = b.find((tag) => tag.Key === aTag.Key);
496
- if (!bTag || bTag.Value !== aTag.Value) {
497
- return false;
498
- }
499
- }
500
- return true;
501
- }
502
- function suffixWithErrors(msg, errors) {
503
- return errors && errors.length > 0 ? `${msg}: ${errors.join(", ")}` : msg;
504
- }
505
- function arrayEquals(a, b) {
506
- return (a.every((item) => b.includes(item)) && b.every((item) => a.includes(item)));
507
- }
508
- function hasReplacement(cs) {
509
- return (cs.Changes ?? []).some((c) => {
510
- // @ts-ignore
511
- const a = c.ResourceChange?.PolicyAction;
512
- return (a === "ReplaceAndDelete" ||
513
- a === "ReplaceAndRetain" ||
514
- a === "ReplaceAndSnapshot");
515
- });
516
- }
@@ -1,3 +0,0 @@
1
- import { SdkProvider } from "sst-aws-cdk/lib/api/aws-auth/sdk-provider.js";
2
- import { DeployStackOptions as PublishStackAssetsOptions } from "./deployments.js";
3
- export declare function publishDeployAssets(sdkProvider: SdkProvider, options: PublishStackAssetsOptions): Promise<any>;
@@ -1,124 +0,0 @@
1
- import * as cxapi from "@aws-cdk/cx-api";
2
- import { AssetManifest } from "cdk-assets";
3
- import { debug } from "sst-aws-cdk/lib/logging.js";
4
- import { CloudFormationStack, TemplateParameters, waitForStackDelete, } from "sst-aws-cdk/lib/api/util/cloudformation.js";
5
- import { addMetadataAssetsToManifest } from "sst-aws-cdk/lib/assets.js";
6
- import { publishAssets } from "sst-aws-cdk/lib/util/asset-publishing.js";
7
- import { AssetManifestBuilder } from "sst-aws-cdk/lib/util/asset-manifest-builder.js";
8
- import { makeBodyParameter } from "sst-aws-cdk/lib/api/util/template-body-parameter.js";
9
- import { Deployments, } from "./deployments.js";
10
- import { lazy } from "../util/lazy.js";
11
- export async function publishDeployAssets(sdkProvider, options) {
12
- const { deployment, envResources, stackSdk, resolvedEnvironment, executionRoleArn, } = await useDeployment().get(sdkProvider, options);
13
- const assetArtifacts = options.stack.dependencies.filter(cxapi.AssetManifestArtifact.isAssetManifestArtifact);
14
- for (const asset of assetArtifacts) {
15
- const manifest = AssetManifest.fromFile(asset.file);
16
- await publishAssets(manifest, sdkProvider, resolvedEnvironment, {
17
- buildAssets: true,
18
- allowCrossAccount: true,
19
- quiet: options.quiet,
20
- parallel: options.assetParallelism,
21
- });
22
- }
23
- return deployStack({
24
- stack: options.stack,
25
- noMonitor: true,
26
- resolvedEnvironment,
27
- deployName: options.deployName,
28
- notificationArns: options.notificationArns,
29
- quiet: options.quiet,
30
- sdk: stackSdk,
31
- sdkProvider,
32
- roleArn: executionRoleArn,
33
- reuseAssets: options.reuseAssets,
34
- envResources,
35
- tags: options.tags,
36
- deploymentMethod: options.deploymentMethod,
37
- force: options.force,
38
- parameters: options.parameters,
39
- usePreviousParameters: options.usePreviousParameters,
40
- progress: options.progress,
41
- ci: options.ci,
42
- rollback: options.rollback,
43
- hotswap: options.hotswap,
44
- extraUserAgent: options.extraUserAgent,
45
- resourcesToImport: options.resourcesToImport,
46
- overrideTemplate: options.overrideTemplate,
47
- assetParallelism: options.assetParallelism,
48
- });
49
- }
50
- const useDeployment = lazy(() => {
51
- const state = new Map();
52
- return {
53
- async get(sdkProvider, options) {
54
- const region = options.stack.environment.region;
55
- if (!state.has(region)) {
56
- const deployment = new Deployments({ sdkProvider });
57
- const env = await deployment.envs.accessStackForMutableStackOperations(options.stack);
58
- const envResources = env.resources;
59
- const executionRoleArn = await env.replacePlaceholders(options.roleArn ?? options.stack.cloudFormationExecutionRoleArn);
60
- // Do a verification of the bootstrap stack version
61
- await deployment.validateBootstrapStackVersion(options.stack.stackName, options.stack.requiresBootstrapStackVersion, options.stack.bootstrapStackVersionSsmParameter, envResources);
62
- state.set(region, {
63
- deployment,
64
- envResources,
65
- stackSdk: env.sdk,
66
- resolvedEnvironment: env.resolvedEnvironment,
67
- executionRoleArn,
68
- });
69
- }
70
- return state.get(region);
71
- },
72
- };
73
- });
74
- async function deployStack(options) {
75
- const stackArtifact = options.stack;
76
- const stackEnv = options.resolvedEnvironment;
77
- options.sdk.appendCustomUserAgent(options.extraUserAgent);
78
- const cfn = options.sdk.cloudFormation();
79
- const deployName = options.deployName || stackArtifact.stackName;
80
- let cloudFormationStack = await CloudFormationStack.lookup(cfn, deployName);
81
- if (cloudFormationStack.stackStatus.isCreationFailure) {
82
- debug(`Found existing stack ${deployName} that had previously failed creation. Deleting it before attempting to re-create it.`);
83
- await cfn.deleteStack({ StackName: deployName });
84
- const deletedStack = await waitForStackDelete(cfn, deployName);
85
- if (deletedStack && deletedStack.stackStatus.name !== "DELETE_COMPLETE") {
86
- throw new Error(`Failed deleting stack ${deployName} that had previously failed creation (current state: ${deletedStack.stackStatus})`);
87
- }
88
- // Update variable to mark that the stack does not exist anymore, but avoid
89
- // doing an actual lookup in CloudFormation (which would be silly to do if
90
- // we just deleted it).
91
- cloudFormationStack = CloudFormationStack.doesNotExist(cfn, deployName);
92
- }
93
- // Detect "legacy" assets (which remain in the metadata) and publish them via
94
- // an ad-hoc asset manifest, while passing their locations via template
95
- // parameters.
96
- const legacyAssets = new AssetManifestBuilder();
97
- const assetParams = await addMetadataAssetsToManifest(stackArtifact, legacyAssets, options.envResources, options.reuseAssets);
98
- const finalParameterValues = { ...options.parameters, ...assetParams };
99
- const templateParams = TemplateParameters.fromTemplate(stackArtifact.template);
100
- const stackParams = options.usePreviousParameters
101
- ? templateParams.updateExisting(finalParameterValues, cloudFormationStack.parameters)
102
- : templateParams.supplyAll(finalParameterValues);
103
- const bodyParameter = await makeBodyParameter(stackArtifact, options.resolvedEnvironment, legacyAssets, options.envResources, options.overrideTemplate);
104
- await publishAssets(legacyAssets.toManifest(stackArtifact.assembly.directory), options.sdkProvider, stackEnv, {
105
- parallel: options.assetParallelism,
106
- allowCrossAccount: true,
107
- });
108
- return {
109
- isUpdate: cloudFormationStack.exists &&
110
- cloudFormationStack.stackStatus.name !== "REVIEW_IN_PROGRESS",
111
- params: {
112
- StackName: deployName,
113
- TemplateBody: bodyParameter.TemplateBody,
114
- TemplateURL: bodyParameter.TemplateURL,
115
- Parameters: stackParams.apiParameters,
116
- Capabilities: [
117
- "CAPABILITY_IAM",
118
- "CAPABILITY_NAMED_IAM",
119
- "CAPABILITY_AUTO_EXPAND",
120
- ],
121
- Tags: options.tags,
122
- },
123
- };
124
- }