-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
localWorkspace.ts
760 lines (728 loc) 路 32.2 KB
/
localWorkspace.ts
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
// Copyright 2016-2021, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as fs from "fs";
import * as yaml from "js-yaml";
import * as os from "os";
import * as semver from "semver";
import * as upath from "upath";
import { CommandResult, runPulumiCmd } from "./cmd";
import { ConfigMap, ConfigValue } from "./config";
import { minimumVersion } from "./minimumVersion";
import { ProjectSettings } from "./projectSettings";
import { OutputMap, Stack } from "./stack";
import { StackSettings, stackSettingsSerDeKeys } from "./stackSettings";
import { Deployment, PluginInfo, PulumiFn, StackSummary, WhoAmIResult, Workspace } from "./workspace";
const SKIP_VERSION_CHECK_VAR = "PULUMI_AUTOMATION_API_SKIP_VERSION_CHECK";
/**
* LocalWorkspace is a default implementation of the Workspace interface.
* A Workspace is the execution context containing a single Pulumi project, a program,
* and multiple stacks. Workspaces are used to manage the execution environment,
* providing various utilities such as plugin installation, environment configuration
* ($PULUMI_HOME), and creation, deletion, and listing of Stacks.
* LocalWorkspace relies on Pulumi.yaml and Pulumi.<stack>.yaml as the intermediate format
* for Project and Stack settings. Modifying ProjectSettings will
* alter the Workspace Pulumi.yaml file, and setting config on a Stack will modify the Pulumi.<stack>.yaml file.
* This is identical to the behavior of Pulumi CLI driven workspaces.
*
* @alpha
*/
export class LocalWorkspace implements Workspace {
/**
* The working directory to run Pulumi CLI commands
*/
readonly workDir: string;
/**
* The directory override for CLI metadata if set.
* This customizes the location of $PULUMI_HOME where metadata is stored and plugins are installed.
*/
readonly pulumiHome?: string;
/**
* The secrets provider to use for encryption and decryption of stack secrets.
* See: https://www.pulumi.com/docs/intro/concepts/secrets/#available-encryption-providers
*/
readonly secretsProvider?: string;
/**
* The inline program `PulumiFn` to be used for Preview/Update operations if any.
* If none is specified, the stack will refer to ProjectSettings for this information.
*/
program?: PulumiFn;
/**
* Environment values scoped to the current workspace. These will be supplied to every Pulumi command.
*/
envVars: { [key: string]: string };
private _pulumiVersion?: semver.SemVer;
/**
* The version of the underlying Pulumi CLI/Engine.
*
* @returns A string representation of the version, if available. `null` otherwise.
*/
public get pulumiVersion(): string {
if (this._pulumiVersion === undefined) {
throw new Error(`Failed to get Pulumi version`);
}
return this._pulumiVersion.toString();
}
private ready: Promise<any[]>;
/**
* Creates a workspace using the specified options. Used for maximal control and customization
* of the underlying environment before any stacks are created or selected.
*
* @param opts Options used to configure the Workspace
*/
static async create(opts: LocalWorkspaceOptions): Promise<LocalWorkspace> {
const ws = new LocalWorkspace(opts);
await ws.ready;
return ws;
}
/**
* Creates a Stack with a LocalWorkspace utilizing the local Pulumi CLI program from the specified workDir.
* This is a way to create drivers on top of pre-existing Pulumi programs. This Workspace will pick up
* any available Settings files (Pulumi.yaml, Pulumi.<stack>.yaml).
*
* @param args A set of arguments to initialize a Stack with a pre-configured Pulumi CLI program that already exists on disk.
* @param opts Additional customizations to be applied to the Workspace.
*/
static async createStack(args: LocalProgramArgs, opts?: LocalWorkspaceOptions): Promise<Stack>;
/**
* Creates a Stack with a LocalWorkspace utilizing the specified inline (in process) Pulumi program.
* This program is fully debuggable and runs in process. If no Project option is specified, default project settings
* will be created on behalf of the user. Similarly, unless a `workDir` option is specified, the working directory
* will default to a new temporary directory provided by the OS.
*
* @param args A set of arguments to initialize a Stack with and inline `PulumiFn` program that runs in process.
* @param opts Additional customizations to be applied to the Workspace.
*/
static async createStack(args: InlineProgramArgs, opts?: LocalWorkspaceOptions): Promise<Stack>;
static async createStack(args: InlineProgramArgs | LocalProgramArgs, opts?: LocalWorkspaceOptions): Promise<Stack> {
if (isInlineProgramArgs(args)) {
return await this.inlineSourceStackHelper(args, Stack.create, opts);
} else if (isLocalProgramArgs(args)) {
return await this.localSourceStackHelper(args, Stack.create, opts);
}
throw new Error(`unexpected args: ${args}`);
}
/**
* Selects a Stack with a LocalWorkspace utilizing the local Pulumi CLI program from the specified workDir.
* This is a way to create drivers on top of pre-existing Pulumi programs. This Workspace will pick up
* any available Settings files (Pulumi.yaml, Pulumi.<stack>.yaml).
*
* @param args A set of arguments to initialize a Stack with a pre-configured Pulumi CLI program that already exists on disk.
* @param opts Additional customizations to be applied to the Workspace.
*/
static async selectStack(args: LocalProgramArgs, opts?: LocalWorkspaceOptions): Promise<Stack>;
/**
* Selects an existing Stack with a LocalWorkspace utilizing the specified inline (in process) Pulumi program.
* This program is fully debuggable and runs in process. If no Project option is specified, default project settings
* will be created on behalf of the user. Similarly, unless a `workDir` option is specified, the working directory
* will default to a new temporary directory provided by the OS.
*
* @param args A set of arguments to initialize a Stack with and inline `PulumiFn` program that runs in process.
* @param opts Additional customizations to be applied to the Workspace.
*/
static async selectStack(args: InlineProgramArgs, opts?: LocalWorkspaceOptions): Promise<Stack>;
static async selectStack(args: InlineProgramArgs | LocalProgramArgs, opts?: LocalWorkspaceOptions): Promise<Stack> {
if (isInlineProgramArgs(args)) {
return await this.inlineSourceStackHelper(args, Stack.select, opts);
} else if (isLocalProgramArgs(args)) {
return await this.localSourceStackHelper(args, Stack.select, opts);
}
throw new Error(`unexpected args: ${args}`);
}
/**
* Creates or selects an existing Stack with a LocalWorkspace utilizing the specified inline (in process) Pulumi CLI program.
* This program is fully debuggable and runs in process. If no Project option is specified, default project settings
* will be created on behalf of the user. Similarly, unless a `workDir` option is specified, the working directory
* will default to a new temporary directory provided by the OS.
*
* @param args A set of arguments to initialize a Stack with a pre-configured Pulumi CLI program that already exists on disk.
* @param opts Additional customizations to be applied to the Workspace.
*/
static async createOrSelectStack(args: LocalProgramArgs, opts?: LocalWorkspaceOptions): Promise<Stack>;
/**
* Creates or selects an existing Stack with a LocalWorkspace utilizing the specified inline Pulumi CLI program.
* This program is fully debuggable and runs in process. If no Project option is specified, default project settings will be created
* on behalf of the user. Similarly, unless a `workDir` option is specified, the working directory will default
* to a new temporary directory provided by the OS.
*
* @param args A set of arguments to initialize a Stack with and inline `PulumiFn` program that runs in process.
* @param opts Additional customizations to be applied to the Workspace.
*/
static async createOrSelectStack(args: InlineProgramArgs, opts?: LocalWorkspaceOptions): Promise<Stack>;
static async createOrSelectStack(args: InlineProgramArgs | LocalProgramArgs, opts?: LocalWorkspaceOptions): Promise<Stack> {
if (isInlineProgramArgs(args)) {
return await this.inlineSourceStackHelper(args, Stack.createOrSelect, opts);
} else if (isLocalProgramArgs(args)) {
return await this.localSourceStackHelper(args, Stack.createOrSelect, opts);
}
throw new Error(`unexpected args: ${args}`);
}
private static async localSourceStackHelper(
args: LocalProgramArgs, initFn: StackInitializer, opts?: LocalWorkspaceOptions,
): Promise<Stack> {
let wsOpts = { workDir: args.workDir };
if (opts) {
wsOpts = { ...opts, workDir: args.workDir };
}
const ws = new LocalWorkspace(wsOpts);
await ws.ready;
return await initFn(args.stackName, ws);
}
private static async inlineSourceStackHelper(
args: InlineProgramArgs, initFn: StackInitializer, opts?: LocalWorkspaceOptions,
): Promise<Stack> {
let wsOpts: LocalWorkspaceOptions = { program: args.program };
if (opts) {
wsOpts = { ...opts, program: args.program };
}
if (!wsOpts.projectSettings) {
if (!!wsOpts.workDir) {
try {
// Try to load the project settings.
loadProjectSettings(wsOpts.workDir);
} catch (e) {
// If it failed to find the project settings file, set a default project.
if (e.toString().includes("failed to find project settings")) {
wsOpts.projectSettings = defaultProject(args.projectName);
} else {
throw e;
}
}
} else {
wsOpts.projectSettings = defaultProject(args.projectName);
}
}
const ws = new LocalWorkspace(wsOpts);
await ws.ready;
return await initFn(args.stackName, ws);
}
private constructor(opts?: LocalWorkspaceOptions) {
let dir = "";
let envs = {};
if (opts) {
const { workDir, pulumiHome, program, envVars, secretsProvider } = opts;
if (workDir) {
dir = workDir;
}
this.pulumiHome = pulumiHome;
this.program = program;
this.secretsProvider = secretsProvider;
envs = { ...envVars };
}
if (!dir) {
dir = fs.mkdtempSync(upath.joinSafe(os.tmpdir(), "automation-"));
}
this.workDir = dir;
this.envVars = envs;
const readinessPromises: Promise<any>[] = [this.getPulumiVersion(minimumVersion)];
if (opts && opts.projectSettings) {
readinessPromises.push(this.saveProjectSettings(opts.projectSettings));
}
if (opts && opts.stackSettings) {
for (const [name, value] of Object.entries(opts.stackSettings)) {
readinessPromises.push(this.saveStackSettings(name, value));
}
}
this.ready = Promise.all(readinessPromises);
}
/**
* Returns the settings object for the current project if any
* LocalWorkspace reads settings from the Pulumi.yaml in the workspace.
* A workspace can contain only a single project at a time.
*/
async projectSettings(): Promise<ProjectSettings> {
return loadProjectSettings(this.workDir);
}
/**
* Overwrites the settings object in the current project.
* There can only be a single project per workspace. Fails if new project name does not match old.
* LocalWorkspace writes this value to a Pulumi.yaml file in Workspace.WorkDir().
*
* @param settings The settings object to save to the Workspace.
*/
async saveProjectSettings(settings: ProjectSettings): Promise<void> {
let foundExt = ".yaml";
for (const ext of settingsExtensions) {
const testPath = upath.joinSafe(this.workDir, `Pulumi${ext}`);
if (fs.existsSync(testPath)) {
foundExt = ext;
break;
}
}
const path = upath.joinSafe(this.workDir, `Pulumi${foundExt}`);
let contents;
if (foundExt === ".json") {
contents = JSON.stringify(settings, null, 4);
}
else {
contents = yaml.safeDump(settings, { skipInvalid: true });
}
return fs.writeFileSync(path, contents);
}
/**
* Returns the settings object for the stack matching the specified stack name if any.
* LocalWorkspace reads this from a Pulumi.<stack>.yaml file in Workspace.WorkDir().
*
* @param stackName The stack to retrieve settings from.
*/
async stackSettings(stackName: string): Promise<StackSettings> {
const stackSettingsName = getStackSettingsName(stackName);
for (const ext of settingsExtensions) {
const isJSON = ext === ".json";
const path = upath.joinSafe(this.workDir, `Pulumi.${stackSettingsName}${ext}`);
if (!fs.existsSync(path)) { continue; }
const contents = fs.readFileSync(path).toString();
let stackSettings: any;
if (isJSON) {
stackSettings = JSON.parse(contents);
}
stackSettings = yaml.safeLoad(contents) as StackSettings;
// Transform the serialized representation back to what we expect.
for (const key of stackSettingsSerDeKeys) {
if (stackSettings.hasOwnProperty(key[0])) {
stackSettings[key[1]] = stackSettings[key[0]];
delete stackSettings[key[0]];
}
}
return stackSettings as StackSettings;
}
throw new Error(`failed to find stack settings file in workdir: ${this.workDir}`);
}
/**
* Overwrites the settings object for the stack matching the specified stack name.
* LocalWorkspace writes this value to a Pulumi.<stack>.yaml file in Workspace.WorkDir()
*
* @param stackName The stack to operate on.
* @param settings The settings object to save.
*/
async saveStackSettings(stackName: string, settings: StackSettings): Promise<void> {
const stackSettingsName = getStackSettingsName(stackName);
let foundExt = ".yaml";
for (const ext of settingsExtensions) {
const testPath = upath.joinSafe(this.workDir, `Pulumi.${stackSettingsName}${ext}`);
if (fs.existsSync(testPath)) {
foundExt = ext;
break;
}
}
const path = upath.joinSafe(this.workDir, `Pulumi.${stackSettingsName}${foundExt}`);
const serializeSettings = settings as any;
let contents;
// Transform the keys to the serialized representation that we expect.
for (const key of stackSettingsSerDeKeys) {
if (serializeSettings.hasOwnProperty(key[1])) {
serializeSettings[key[0]] = serializeSettings[key[1]];
delete serializeSettings[key[1]];
}
}
if (foundExt === ".json") {
contents = JSON.stringify(serializeSettings, null, 4);
}
else {
contents = yaml.safeDump(serializeSettings, { skipInvalid: true });
}
return fs.writeFileSync(path, contents);
}
/**
* Creates and sets a new stack with the stack name, failing if one already exists.
*
* @param stackName The stack to create.
*/
async createStack(stackName: string): Promise<void> {
const args = ["stack", "init", stackName];
if (this.secretsProvider) {
args.push("--secrets-provider", this.secretsProvider);
}
await this.runPulumiCmd(args);
}
/**
* Selects and sets an existing stack matching the stack name, failing if none exists.
*
* @param stackName The stack to select.
*/
async selectStack(stackName: string): Promise<void> {
await this.runPulumiCmd(["stack", "select", stackName]);
}
/**
* Deletes the stack and all associated configuration and history.
*
* @param stackName The stack to remove
*/
async removeStack(stackName: string): Promise<void> {
await this.runPulumiCmd(["stack", "rm", "--yes", stackName]);
}
/**
* Returns the value associated with the specified stack name and key,
* scoped to the current workspace. LocalWorkspace reads this config from the matching Pulumi.stack.yaml file.
*
* @param stackName The stack to read config from
* @param key The key to use for the config lookup
*/
async getConfig(stackName: string, key: string): Promise<ConfigValue> {
const result = await this.runPulumiCmd(["config", "get", key, "--json", "--stack", stackName]);
return JSON.parse(result.stdout);
}
/**
* Returns the config map for the specified stack name, scoped to the current workspace.
* LocalWorkspace reads this config from the matching Pulumi.stack.yaml file.
*
* @param stackName The stack to read config from
*/
async getAllConfig(stackName: string): Promise<ConfigMap> {
const result = await this.runPulumiCmd(["config", "--show-secrets", "--json", "--stack", stackName]);
return JSON.parse(result.stdout);
}
/**
* Sets the specified key-value pair on the provided stack name.
* LocalWorkspace writes this value to the matching Pulumi.<stack>.yaml file in Workspace.WorkDir().
*
* @param stackName The stack to operate on
* @param key The config key to set
* @param value The value to set
*/
async setConfig(stackName: string, key: string, value: ConfigValue): Promise<void> {
const secretArg = value.secret ? "--secret" : "--plaintext";
await this.runPulumiCmd(["config", "set", key, "--stack", stackName, secretArg, "--non-interactive", "--", value.value]);
}
/**
* Sets all values in the provided config map for the specified stack name.
* LocalWorkspace writes the config to the matching Pulumi.<stack>.yaml file in Workspace.WorkDir().
*
* @param stackName The stack to operate on
* @param config The `ConfigMap` to upsert against the existing config.
*/
async setAllConfig(stackName: string, config: ConfigMap): Promise<void> {
let args = ["config", "set-all", "--stack", stackName];
for (const [key, value] of Object.entries(config)) {
const secretArg = value.secret ? "--secret" : "--plaintext";
args = [...args, secretArg, `${key}=${value.value}`];
}
await this.runPulumiCmd(args);
}
/**
* Removes the specified key-value pair on the provided stack name.
* It will remove any matching values in the Pulumi.<stack>.yaml file in Workspace.WorkDir().
*
* @param stackName The stack to operate on
* @param key The config key to remove
*/
async removeConfig(stackName: string, key: string): Promise<void> {
await this.runPulumiCmd(["config", "rm", key, "--stack", stackName]);
}
/**
*
* Removes all values in the provided key list for the specified stack name
* It will remove any matching values in the Pulumi.<stack>.yaml file in Workspace.WorkDir().
*
* @param stackName The stack to operate on
* @param keys The list of keys to remove from the underlying config
*/
async removeAllConfig(stackName: string, keys: string[]): Promise<void> {
await this.runPulumiCmd(["config", "rm-all", "--stack", stackName, ...keys]);
}
/**
* Gets and sets the config map used with the last update for Stack matching stack name.
* It will overwrite all configuration in the Pulumi.<stack>.yaml file in Workspace.WorkDir().
*
* @param stackName The stack to refresh
*/
async refreshConfig(stackName: string): Promise<ConfigMap> {
await this.runPulumiCmd(["config", "refresh", "--force", "--stack", stackName]);
return this.getAllConfig(stackName);
}
/**
* Returns the currently authenticated user.
*/
async whoAmI(): Promise<WhoAmIResult> {
const result = await this.runPulumiCmd(["whoami"]);
return { user: result.stdout.trim() };
}
/**
* Returns a summary of the currently selected stack, if any.
*/
async stack(): Promise<StackSummary | undefined> {
const stacks = await this.listStacks();
for (const stack of stacks) {
if (stack.current) {
return stack;
}
}
return undefined;
}
/**
* Returns all Stacks created under the current Project.
* This queries underlying backend and may return stacks not present in the Workspace (as Pulumi.<stack>.yaml files).
*/
async listStacks(): Promise<StackSummary[]> {
const result = await this.runPulumiCmd(["stack", "ls", "--json"]);
return JSON.parse(result.stdout);
}
/**
* Installs a plugin in the Workspace, for example to use cloud providers like AWS or GCP.
*
* @param name the name of the plugin.
* @param version the version of the plugin e.g. "v1.0.0".
* @param kind the kind of plugin, defaults to "resource"
*/
async installPlugin(name: string, version: string): Promise<void> {
await this.runPulumiCmd(["plugin", "install", "resource", name, version]);
}
/**
* Installs a plugin in the Workspace, from a third party server.
*
* @param name the name of the plugin.
* @param version the version of the plugin e.g. "v1.0.0".
* @param kind the kind of plugin, defaults to "resource"
* @param server the server to install the plugin from
*/
async installPluginFromServer(name: string, version: string, server: string): Promise<void> {
await this.runPulumiCmd(["plugin", "install", "resource", name, version, "--server", server]);
}
/**
* Removes a plugin from the Workspace matching the specified name and version.
*
* @param name the optional name of the plugin.
* @param versionRange optional semver range to check when removing plugins matching the given name
* e.g. "1.0.0", ">1.0.0".
* @param kind he kind of plugin, defaults to "resource".
*/
async removePlugin(name?: string, versionRange?: string): Promise<void> {
const args = ["plugin", "rm", "resource"];
if (name) {
args.push(name);
}
if (versionRange) {
args.push(versionRange);
}
args.push("--yes");
await this.runPulumiCmd(args);
}
/**
* Returns a list of all plugins installed in the Workspace.
*/
async listPlugins(): Promise<PluginInfo[]> {
const result = await this.runPulumiCmd(["plugin", "ls", "--json"]);
return JSON.parse(result.stdout, (key, value) => {
if (key === "installTime" || key === "lastUsedTime") {
return new Date(value);
}
return value;
});
}
/**
* exportStack exports the deployment state of the stack.
* This can be combined with Workspace.importStack to edit a stack's state (such as recovery from failed deployments).
*
* @param stackName the name of the stack.
*/
async exportStack(stackName: string): Promise<Deployment> {
const result = await this.runPulumiCmd(["stack", "export", "--show-secrets", "--stack", stackName]);
return JSON.parse(result.stdout);
}
/**
* importStack imports the specified deployment state into a pre-existing stack.
* This can be combined with Workspace.exportStack to edit a stack's state (such as recovery from failed deployments).
*
* @param stackName the name of the stack.
* @param state the stack state to import.
*/
async importStack(stackName: string, state: Deployment): Promise<void> {
const randomSuffix = Math.floor(100000 + Math.random() * 900000);
const filepath = upath.joinSafe(os.tmpdir(), `automation-${randomSuffix}`);
const contents = JSON.stringify(state, null, 4);
fs.writeFileSync(filepath, contents);
await this.runPulumiCmd(["stack", "import", "--file", filepath, "--stack", stackName]);
fs.unlinkSync(filepath);
}
/**
* Gets the current set of Stack outputs from the last Stack.up().
* @param stackName the name of the stack.
*/
async stackOutputs(stackName: string): Promise<OutputMap> {
// TODO: do this in parallel after this is fixed https://github.com/pulumi/pulumi/issues/6050
const maskedResult = await this.runPulumiCmd(["stack", "output", "--json", "--stack", stackName]);
const plaintextResult = await this.runPulumiCmd(["stack", "output", "--json", "--show-secrets", "--stack", stackName]);
const maskedOuts = JSON.parse(maskedResult.stdout);
const plaintextOuts = JSON.parse(plaintextResult.stdout);
const outputs: OutputMap = {};
for (const [key, value] of Object.entries(plaintextOuts)) {
const secret = maskedOuts[key] === "[secret]";
outputs[key] = { value, secret };
}
return outputs;
}
/**
* serializeArgsForOp is hook to provide additional args to every CLI commands before they are executed.
* Provided with stack name,
* returns a list of args to append to an invoked command ["--config=...", ]
* LocalWorkspace does not utilize this extensibility point.
*/
async serializeArgsForOp(_: string): Promise<string[]> {
// LocalWorkspace does not utilize this extensibility point.
return [];
}
/**
* postCommandCallback is a hook executed after every command. Called with the stack name.
* An extensibility point to perform workspace cleanup (CLI operations may create/modify a Pulumi.stack.yaml)
* LocalWorkspace does not utilize this extensibility point.
*/
async postCommandCallback(_: string): Promise<void> {
// LocalWorkspace does not utilize this extensibility point.
return;
}
private async getPulumiVersion(minVersion: semver.SemVer) {
const result = await this.runPulumiCmd(["version"]);
const optOut = !!this.envVars[SKIP_VERSION_CHECK_VAR] || !!process.env[SKIP_VERSION_CHECK_VAR];
const version = parseAndValidatePulumiVersion(minVersion, result.stdout.trim(), optOut);
if (version != null) {
this._pulumiVersion = version;
}
}
private async runPulumiCmd(
args: string[],
): Promise<CommandResult> {
let envs: { [key: string]: string } = {};
if (this.pulumiHome) {
envs["PULUMI_HOME"] = this.pulumiHome;
}
envs = { ...envs, ...this.envVars };
return runPulumiCmd(args, this.workDir, envs);
}
}
/**
* Description of a stack backed by an inline (in process) Pulumi program.
*/
export interface InlineProgramArgs {
/**
* The name of the associated Stack
*/
stackName: string;
/**
* The name of the associated project
*/
projectName: string;
/**
* The inline (in process) Pulumi program to use with Update and Preview operations.
*/
program: PulumiFn;
}
/**
* Description of a stack backed by pre-existing local Pulumi CLI program.
*/
export interface LocalProgramArgs {
stackName: string;
workDir: string;
}
/**
* Extensibility options to configure a LocalWorkspace; e.g: settings to seed
* and environment variables to pass through to every command.
*/
export interface LocalWorkspaceOptions {
/**
* The directory to run Pulumi commands and read settings (Pulumi.yaml and Pulumi.<stack>.yaml)l.
*/
workDir?: string;
/**
* The directory to override for CLI metadata
*/
pulumiHome?: string;
/**
* The inline program `PulumiFn` to be used for Preview/Update operations if any.
* If none is specified, the stack will refer to ProjectSettings for this information.
*/
program?: PulumiFn;
/**
* Environment values scoped to the current workspace. These will be supplied to every Pulumi command.
*/
envVars?: { [key: string]: string };
/**
* The secrets provider to use for encryption and decryption of stack secrets.
* See: https://www.pulumi.com/docs/intro/concepts/secrets/#available-encryption-providers
*/
secretsProvider?: string;
/**
* The settings object for the current project.
*/
projectSettings?: ProjectSettings;
/**
* A map of Stack names and corresponding settings objects.
*/
stackSettings?: { [key: string]: StackSettings };
}
/**
* Returns true if the provided `args` object satisfies the `LocalProgramArgs` interface.
*
* @param args The args object to evaluate
*/
function isLocalProgramArgs(args: LocalProgramArgs | InlineProgramArgs): args is LocalProgramArgs {
return (args as LocalProgramArgs).workDir !== undefined;
}
/**
* Returns true if the provided `args` object satisfies the `InlineProgramArgs` interface.
*
* @param args The args object to evaluate
*/
function isInlineProgramArgs(args: LocalProgramArgs | InlineProgramArgs): args is InlineProgramArgs {
return (args as InlineProgramArgs).projectName !== undefined &&
(args as InlineProgramArgs).program !== undefined;
}
const settingsExtensions = [".yaml", ".yml", ".json"];
function getStackSettingsName(name: string): string {
const parts = name.split("/");
if (parts.length < 1) {
return name;
}
return parts[parts.length - 1];
}
type StackInitializer = (name: string, workspace: Workspace) => Promise<Stack>;
function defaultProject(projectName: string) {
const settings: ProjectSettings = { name: projectName, runtime: "nodejs", main: process.cwd() };
return settings;
}
function loadProjectSettings(workDir: string) {
for (const ext of settingsExtensions) {
const isJSON = ext === ".json";
const path = upath.joinSafe(workDir, `Pulumi${ext}`);
if (!fs.existsSync(path)) { continue; }
const contents = fs.readFileSync(path).toString();
if (isJSON) {
return JSON.parse(contents);
}
return yaml.safeLoad(contents) as ProjectSettings;
}
throw new Error(`failed to find project settings file in workdir: ${workDir}`);
}
/**
* @internal
* Throws an error if the Pulumi CLI version is not valid.
*
* @param minVersion The minimum acceptable version of the Pulumi CLI.
* @param currentVersion The currently known version. `null` indicates that the current version is unknown.
* @paramoptOut If the user has opted out of the version check.
*/
export function parseAndValidatePulumiVersion(minVersion: semver.SemVer, currentVersion: string, optOut: boolean): semver.SemVer | null {
const version = semver.parse(currentVersion);
if (optOut) {
return version;
}
if (version == null) {
throw new Error(`Failed to parse Pulumi CLI version. This is probably an internal error. You can override this by setting "${SKIP_VERSION_CHECK_VAR}" to "true".`);
}
if (minVersion.major < version.major) {
throw new Error(`Major version mismatch. You are using Pulumi CLI version ${currentVersion.toString()} with Automation SDK v${minVersion.major}. Please update the SDK.`);
}
if (minVersion.compare(version) === 1) {
throw new Error(`Minimum version requirement failed. The minimum CLI version requirement is ${minVersion.toString()}, your current CLI version is ${currentVersion.toString()}. Please update the Pulumi CLI.`);
}
return version;
}