-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
cli.ts
353 lines (315 loc) · 11.5 KB
/
cli.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
// eslint-disable-next-line import/no-extraneous-dependencies
import { exec as runCli } from 'aws-cdk/lib';
// eslint-disable-next-line import/no-extraneous-dependencies
import { createAssembly, prepareContext, prepareDefaultEnvironment } from 'aws-cdk/lib/api/cxapp/exec';
import { SharedOptions, DeployOptions, DestroyOptions, BootstrapOptions, SynthOptions, ListOptions, StackActivityProgress, HotswapMode } from './commands';
/**
* AWS CDK CLI operations
*/
export interface IAwsCdkCli {
/**
* cdk list
*/
list(options?: ListOptions): Promise<void>;
/**
* cdk synth
*/
synth(options?: SynthOptions): Promise<void>;
/**
* cdk bootstrap
*/
bootstrap(options?: BootstrapOptions): Promise<void>;
/**
* cdk deploy
*/
deploy(options?: DeployOptions): Promise<void>;
/**
* cdk destroy
*/
destroy(options?: DestroyOptions): Promise<void>;
}
/**
* Configuration for creating a CLI from an AWS CDK App directory
*/
export interface CdkAppDirectoryProps {
/**
* Command-line for executing your app or a cloud assembly directory
* e.g. "node bin/my-app.js"
* or
* "cdk.out"
*
* @default - read from cdk.json
*/
readonly app?: string;
/**
* Emits the synthesized cloud assembly into a directory
*
* @default cdk.out
*/
readonly output?: string;
}
/**
* A class returning the path to a Cloud Assembly Directory when its `produce` method is invoked with the current context
*
* AWS CDK apps might need to be synthesized multiple times with additional context values before they are ready.
* When running the CLI from inside a directory, this is implemented by invoking the app multiple times.
* Here the `produce()` method provides this multi-pass ability.
*/
export interface ICloudAssemblyDirectoryProducer {
/**
* The working directory used to run the Cloud Assembly from.
* This is were a `cdk.context.json` files will be written.
*
* @default - current working directory
*/
workingDirectory?: string;
/**
* Synthesize a Cloud Assembly directory for a given context.
*
* For all features to work correctly, `cdk.App()` must be instantiated with the received context values in the method body.
* Usually obtained similar to this:
* ```ts fixture=imports
* class MyProducer implements ICloudAssemblyDirectoryProducer {
* async produce(context: Record<string, any>) {
* const app = new cdk.App({ context });
* // create stacks here
* return app.synth().directory;
* }
* }
* ```
*/
produce(context: Record<string, any>): Promise<string>;
}
/**
* Provides a programmatic interface for interacting with the AWS CDK CLI
*/
export class AwsCdkCli implements IAwsCdkCli {
/**
* Create the CLI from a directory containing an AWS CDK app
* @param directory the directory of the AWS CDK app. Defaults to the current working directory.
* @param props additional configuration properties
* @returns an instance of `AwsCdkCli`
*/
public static fromCdkAppDirectory(directory?: string, props: CdkAppDirectoryProps = {}) {
return new AwsCdkCli(async (args) => changeDir(
() => {
if (props.app) {
args.push('--app', props.app);
}
if (props.output) {
args.push('--output', props.output);
}
return runCli(args);
},
directory,
));
}
/**
* Create the CLI from a CloudAssemblyDirectoryProducer
*/
public static fromCloudAssemblyDirectoryProducer(producer: ICloudAssemblyDirectoryProducer) {
return new AwsCdkCli(async (args) => changeDir(
() => runCli(args, async (sdk, config) => {
const env = await prepareDefaultEnvironment(sdk);
const context = await prepareContext(config, env);
return withEnv(async() => createAssembly(await producer.produce(context)), env);
}),
producer.workingDirectory,
));
}
private constructor(
private readonly cli: (args: string[]) => Promise<number | void>,
) {}
/**
* Execute the CLI with a list of arguments
*/
private async exec(args: string[]) {
return this.cli(args);
}
/**
* cdk list
*/
public async list(options: ListOptions = {}) {
const listCommandArgs: string[] = [
...renderBooleanArg('long', options.long),
...this.createDefaultArguments(options),
];
await this.exec(['ls', ...listCommandArgs]);
}
/**
* cdk synth
*/
public async synth(options: SynthOptions = {}) {
const synthCommandArgs: string[] = [
...renderBooleanArg('validation', options.validation),
...renderBooleanArg('quiet', options.quiet),
...renderBooleanArg('exclusively', options.exclusively),
...this.createDefaultArguments(options),
];
await this.exec(['synth', ...synthCommandArgs]);
}
/**
* cdk bootstrap
*/
public async bootstrap(options: BootstrapOptions = {}) {
const envs = options.environments ?? [];
const bootstrapCommandArgs: string[] = [
...envs,
...renderBooleanArg('force', options.force),
...renderBooleanArg('show-template', options.showTemplate),
...renderBooleanArg('terminationProtection', options.terminationProtection),
...renderBooleanArg('example-permissions-boundary', options.examplePermissionsBoundary),
...renderBooleanArg('terminationProtection', options.usePreviousParameters),
...renderBooleanArg('execute', options.execute),
...options.toolkitStackName ? ['--toolkit-stack-name', options.toolkitStackName] : [],
...options.bootstrapBucketName ? ['--bootstrap-bucket-name', options.bootstrapBucketName] : [],
...options.cfnExecutionPolicy ? ['--cloudformation-execution-policies', options.cfnExecutionPolicy] : [],
...options.template ? ['--template', options.template] : [],
...options.customPermissionsBoundary ? ['--custom-permissions-boundary', options.customPermissionsBoundary] : [],
...options.qualifier ? ['--qualifier', options.qualifier] : [],
...options.trust ? ['--trust', options.trust] : [],
...options.trustForLookup ? ['--trust-for-lookup', options.trustForLookup] : [],
...options.bootstrapKmsKeyId ? ['--bootstrap-kms-key-id', options.bootstrapKmsKeyId] : [],
...options.bootstrapCustomerKey ? ['--bootstrap-customer-key', options.bootstrapCustomerKey] : [],
...options.publicAccessBlockConfiguration ? ['--public-access-block-configuration', options.publicAccessBlockConfiguration] : [],
...this.createDefaultArguments(options),
];
await this.exec(['bootstrap', ...bootstrapCommandArgs]);
}
/**
* cdk deploy
*/
public async deploy(options: DeployOptions = {}) {
const deployCommandArgs: string[] = [
...renderBooleanArg('ci', options.ci),
...renderBooleanArg('execute', options.execute),
...renderBooleanArg('exclusively', options.exclusively),
...renderBooleanArg('force', options.force),
...renderBooleanArg('previous-parameters', options.usePreviousParameters),
...renderBooleanArg('rollback', options.rollback),
...renderBooleanArg('staging', options.staging),
...renderBooleanArg('asset-parallelism', options.assetParallelism),
...renderBooleanArg('asset-prebuild', options.assetPrebuild),
...renderNumberArg('concurrency', options.concurrency),
...renderHotswapArg(options.hotswap),
...options.reuseAssets ? renderArrayArg('--reuse-assets', options.reuseAssets) : [],
...options.notificationArns ? renderArrayArg('--notification-arns', options.notificationArns) : [],
...options.parameters ? renderMapArrayArg('--parameters', options.parameters) : [],
...options.outputsFile ? ['--outputs-file', options.outputsFile] : [],
...options.requireApproval ? ['--require-approval', options.requireApproval] : [],
...options.changeSetName ? ['--change-set-name', options.changeSetName] : [],
...options.toolkitStackName ? ['--toolkit-stack-name', options.toolkitStackName] : [],
...options.progress ? ['--progress', options.progress] : ['--progress', StackActivityProgress.EVENTS],
...this.createDefaultArguments(options),
];
await this.exec(['deploy', ...deployCommandArgs]);
}
/**
* cdk destroy
*/
public async destroy(options: DestroyOptions = {}) {
const destroyCommandArgs: string[] = [
...options.requireApproval ? [] : ['--force'],
...renderBooleanArg('exclusively', options.exclusively),
...this.createDefaultArguments(options),
];
await this.exec(['destroy', ...destroyCommandArgs]);
}
/**
* Configure default arguments shared by all commands
*/
private createDefaultArguments(options: SharedOptions): string[] {
const stacks = options.stacks ?? ['--all'];
return [
...renderBooleanArg('strict', options.strict),
...renderBooleanArg('trace', options.trace),
...renderBooleanArg('lookups', options.lookups),
...renderBooleanArg('ignore-errors', options.ignoreErrors),
...renderBooleanArg('json', options.json),
...renderBooleanArg('verbose', options.verbose),
...renderBooleanArg('debug', options.debug),
...renderBooleanArg('ec2creds', options.ec2Creds),
...renderBooleanArg('version-reporting', options.versionReporting),
...renderBooleanArg('path-metadata', options.pathMetadata),
...renderBooleanArg('asset-metadata', options.assetMetadata),
...renderBooleanArg('notices', options.notices),
...renderBooleanArg('color', options.color ?? (process.env.NO_COLOR ? false : undefined)),
...options.context ? renderMapArrayArg('--context', options.context) : [],
...options.profile ? ['--profile', options.profile] : [],
...options.proxy ? ['--proxy', options.proxy] : [],
...options.caBundlePath ? ['--ca-bundle-path', options.caBundlePath] : [],
...options.roleArn ? ['--role-arn', options.roleArn] : [],
...stacks,
];
}
}
function renderHotswapArg(hotswapMode: HotswapMode | undefined): string[] {
switch (hotswapMode) {
case HotswapMode.FALL_BACK:
return ['--hotswap-fallback'];
case HotswapMode.HOTSWAP_ONLY:
return ['--hotswap'];
default:
return [];
}
}
function renderMapArrayArg(flag: string, parameters: { [name: string]: string | undefined }): string[] {
const params: string[] = [];
for (const [key, value] of Object.entries(parameters)) {
params.push(`${key}=${value}`);
}
return renderArrayArg(flag, params);
}
function renderArrayArg(flag: string, values?: string[]): string[] {
let args: string[] = [];
for (const value of values ?? []) {
args.push(flag, value);
}
return args;
}
function renderBooleanArg(arg: string, value?: boolean): string[] {
if (value) {
return [`--${arg}`];
} else if (value === undefined) {
return [];
} else {
return [`--no-${arg}`];
}
}
function renderNumberArg(arg: string, value?: number): string[] {
if (typeof value === 'undefined') {
return [];
}
return [`--${arg}`, value.toString(10)];
}
/**
* Run code from a different working directory
*/
async function changeDir(block: () => Promise<any>, workingDir?: string) {
const originalWorkingDir = process.cwd();
try {
if (workingDir) {
process.chdir(workingDir);
}
return await block();
} finally {
if (workingDir) {
process.chdir(originalWorkingDir);
}
}
}
/**
* Run code with additional environment variables
*/
async function withEnv(block: () => Promise<any>, env: Record<string, string> = {}) {
const originalEnv = process.env;
try {
process.env = {
...originalEnv,
...env,
};
return await block();
} finally {
process.env = originalEnv;
}
}