-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathcfn-include.ts
470 lines (418 loc) · 17.7 KB
/
cfn-include.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
import * as core from '@aws-cdk/core';
import * as cfn_parse from '@aws-cdk/core/lib/cfn-parse';
import * as cfn_type_to_l1_mapping from './cfn-type-to-l1-mapping';
import * as futils from './file-utils';
/**
* Construction properties of {@link CfnInclude}.
*/
export interface CfnIncludeProps {
/**
* Path to the template file.
*
* Both JSON and YAML template formats are supported.
*/
readonly templateFile: string;
/**
* Specifies the template files that define nested stacks that should be included.
*
* If your template specifies a stack that isn't included here, it won't be created as a NestedStack
* resource, and it won't be accessible from {@link CfnInclude.getNestedStack}.
*
* If you include a stack here with an ID that isn't in the template,
* or is in the template but is not a nested stack,
* template creation will fail and an error will be thrown.
*
* @default - no nested stacks will be included
*/
readonly nestedStacks?: { [stackName: string]: CfnIncludeProps };
/**
* Specifies parameters to be replaced by the values in this mapping.
* Any parameters in the template that aren't specified here will be left unmodified.
* If you include a parameter here with an ID that isn't in the template,
* template creation will fail and an error will be thrown.
*
* @default - no parameters will be replaced
*/
readonly parameters?: { [parameterName: string]: any };
}
/**
* The type returned from {@link CfnInclude.getNestedStack}.
* Contains both the NestedStack object and
* CfnInclude representations of the child stack.
*/
export interface IncludedNestedStack {
/**
* The NestedStack object which respresents the scope of the template.
*/
readonly stack: core.NestedStack;
/**
* The CfnInclude that respresents the template, which can
* be used to access Resources and other template elements.
*/
readonly includedTemplate: CfnInclude;
}
/**
* Construct to import an existing CloudFormation template file into a CDK application.
* All resources defined in the template file can be retrieved by calling the {@link getResource} method.
* Any modifications made on the returned resource objects will be reflected in the resulting CDK template.
*/
export class CfnInclude extends core.CfnElement {
private readonly conditions: { [conditionName: string]: core.CfnCondition } = {};
private readonly conditionsScope: core.Construct;
private readonly resources: { [logicalId: string]: core.CfnResource } = {};
private readonly parameters: { [logicalId: string]: core.CfnParameter } = {};
private readonly parametersToReplace: { [parameterName: string]: any };
private readonly outputs: { [logicalId: string]: core.CfnOutput } = {};
private readonly nestedStacks: { [logicalId: string]: IncludedNestedStack } = {};
private readonly nestedStacksToInclude: { [name: string]: CfnIncludeProps };
private readonly template: any;
private readonly preserveLogicalIds: boolean;
constructor(scope: core.Construct, id: string, props: CfnIncludeProps) {
super(scope, id);
this.parametersToReplace = props.parameters || {};
// read the template into a JS object
this.template = futils.readYamlSync(props.templateFile);
// ToDo implement preserveLogicalIds=false
this.preserveLogicalIds = true;
// check if all user specified parameter values exist in the template
for (const logicalId of Object.keys(this.parametersToReplace)) {
if (!(logicalId in (this.template.Parameters || {}))) {
throw new Error(`Parameter with logical ID '${logicalId}' was not found in the template`);
}
}
// instantiate all parameters
for (const logicalId of Object.keys(this.template.Parameters || {})) {
this.createParameter(logicalId);
}
// instantiate the conditions
this.conditionsScope = new core.Construct(this, '$Conditions');
for (const conditionName of Object.keys(this.template.Conditions || {})) {
this.getOrCreateCondition(conditionName);
}
this.nestedStacksToInclude = props.nestedStacks || {};
// instantiate all resources as CDK L1 objects
for (const logicalId of Object.keys(this.template.Resources || {})) {
this.getOrCreateResource(logicalId);
}
// verify that all nestedStacks have been instantiated
for (const nestedStackId of Object.keys(props.nestedStacks || {})) {
if (!(nestedStackId in this.resources)) {
throw new Error(`Nested Stack with logical ID '${nestedStackId}' was not found in the template`);
}
}
const outputScope = new core.Construct(this, '$Ouputs');
for (const logicalId of Object.keys(this.template.Outputs || {})) {
this.createOutput(logicalId, outputScope);
}
}
/**
* Returns the low-level CfnResource from the template with the given logical ID.
* Any modifications performed on that resource will be reflected in the resulting CDK template.
*
* The returned object will be of the proper underlying class;
* you can always cast it to the correct type in your code:
*
* // assume the template contains an AWS::S3::Bucket with logical ID 'Bucket'
* const cfnBucket = cfnTemplate.getResource('Bucket') as s3.CfnBucket;
* // cfnBucket is of type s3.CfnBucket
*
* If the template does not contain a resource with the given logical ID,
* an exception will be thrown.
*
* @param logicalId the logical ID of the resource in the CloudFormation template file
*/
public getResource(logicalId: string): core.CfnResource {
const ret = this.resources[logicalId];
if (!ret) {
throw new Error(`Resource with logical ID '${logicalId}' was not found in the template`);
}
return ret;
}
/**
* Returns the CfnCondition object from the 'Conditions'
* section of the CloudFormation template with the given name.
* Any modifications performed on that object will be reflected in the resulting CDK template.
*
* If a Condition with the given name is not present in the template,
* throws an exception.
*
* @param conditionName the name of the Condition in the CloudFormation template file
*/
public getCondition(conditionName: string): core.CfnCondition {
const ret = this.conditions[conditionName];
if (!ret) {
throw new Error(`Condition with name '${conditionName}' was not found in the template`);
}
return ret;
}
/**
* Returns the CfnParameter object from the 'Parameters'
* section of the included template
* Any modifications performed on that object will be reflected in the resulting CDK template.
*
* If a Parameter with the given name is not present in the template,
* throws an exception.
*
* @param parameterName the name of the parameter to retrieve
*/
public getParameter(parameterName: string): core.CfnParameter {
const ret = this.parameters[parameterName];
if (!ret) {
throw new Error(`Parameter with name '${parameterName}' was not found in the template`);
}
return ret;
}
/**
* Returns the CfnOutput object from the 'Outputs'
* section of the included template
* Any modifications performed on that object will be reflected in the resulting CDK template.
*
* If an Output with the given name is not present in the template,
* throws an exception.
*
* @param logicalId the name of the output to retrieve
*/
public getOutput(logicalId: string): core.CfnOutput {
const ret = this.outputs[logicalId];
if (!ret) {
throw new Error(`Output with logical ID '${logicalId}' was not found in the template`);
}
return ret;
}
/**
* Returns the NestedStack with name logicalId.
* For a nested stack to be returned by this method, it must be specified in the {@link CfnIncludeProps.nestedStacks}
* @param logicalId the ID of the stack to retrieve, as it appears in the template.
*/
public getNestedStack(logicalId: string): IncludedNestedStack {
if (!this.nestedStacks[logicalId]) {
if (!this.template.Resources[logicalId]) {
throw new Error(`Nested Stack with logical ID '${logicalId}' was not found in the template`);
} else if (this.template.Resources[logicalId].Type !== 'AWS::CloudFormation::Stack') {
throw new Error(`Resource with logical ID '${logicalId}' is not a CloudFormation Stack`);
} else {
throw new Error(`Nested Stack '${logicalId}' was not included in the nestedStacks property when including the parent template`);
}
}
return this.nestedStacks[logicalId];
}
/** @internal */
public _toCloudFormation(): object {
const ret: { [section: string]: any } = {};
for (const section of Object.keys(this.template)) {
const self = this;
const finder: cfn_parse.ICfnFinder = {
findResource(lId): core.CfnResource | undefined {
return self.resources[lId];
},
findRefTarget(elementName: string): core.CfnElement | undefined {
return self.resources[elementName] ?? self.parameters[elementName];
},
findCondition(conditionName: string): core.CfnCondition | undefined {
return self.conditions[conditionName];
},
};
const cfnParser = new cfn_parse.CfnParser({
finder,
parameters: this.parametersToReplace,
});
switch (section) {
case 'Conditions':
case 'Resources':
case 'Parameters':
case 'Outputs':
// these are rendered as a side effect of instantiating the L1s
break;
default:
ret[section] = cfnParser.parseValue(this.template[section]);
}
}
return ret;
}
private createParameter(logicalId: string): void {
if (logicalId in this.parametersToReplace) {
return;
}
const expression = new cfn_parse.CfnParser({
finder: {
findResource() { throw new Error('Using GetAtt expressions in Parameter definitions is not allowed'); },
findRefTarget() { throw new Error('Using Ref expressions in Parameter definitions is not allowed'); },
findCondition() { throw new Error('Referring to Conditions in Parameter definitions is not allowed'); },
},
}).parseValue(this.template.Parameters[logicalId]);
const cfnParameter = new core.CfnParameter(this, logicalId, {
type: expression.Type,
default: expression.Default,
allowedPattern: expression.AllowedPattern,
allowedValues: expression.AllowedValues,
constraintDescription: expression.ConstraintDescription,
description: expression.Description,
maxLength: expression.MaxLength,
maxValue: expression.MaxValue,
minLength: expression.MinLength,
minValue: expression.MinValue,
noEcho: expression.NoEcho,
});
cfnParameter.overrideLogicalId(logicalId);
this.parameters[logicalId] = cfnParameter;
}
private createOutput(logicalId: string, scope: core.Construct): void {
const self = this;
const outputAttributes = new cfn_parse.CfnParser({
finder: {
findResource(lId): core.CfnResource | undefined {
return self.resources[lId];
},
findRefTarget(elementName: string): core.CfnElement | undefined {
return self.resources[elementName] ?? self.parameters[elementName];
},
findCondition(): undefined {
return undefined;
},
},
parameters: this.parametersToReplace,
}).parseValue(this.template.Outputs[logicalId]);
const cfnOutput = new core.CfnOutput(scope, logicalId, {
value: outputAttributes.Value,
description: outputAttributes.Description,
exportName: outputAttributes.Export ? outputAttributes.Export.Name : undefined,
condition: (() => {
if (!outputAttributes.Condition) {
return undefined;
} else if (this.conditions[outputAttributes.Condition]) {
return self.getCondition(outputAttributes.Condition);
}
throw new Error(`Output with name '${logicalId}' refers to a Condition with name ` +
`'${outputAttributes.Condition}' which was not found in this template`);
})(),
});
cfnOutput.overrideLogicalId(logicalId);
this.outputs[logicalId] = cfnOutput;
}
private getOrCreateCondition(conditionName: string): core.CfnCondition {
if (conditionName in this.conditions) {
return this.conditions[conditionName];
}
const self = this;
const cfnParser = new cfn_parse.CfnParser({
finder: {
findResource() { throw new Error('Using GetAtt in Condition definitions is not allowed'); },
findRefTarget(elementName: string): core.CfnElement | undefined {
// only Parameters can be referenced in the 'Conditions' section
return self.parameters[elementName];
},
findCondition(cName: string): core.CfnCondition | undefined {
return cName in (self.template.Conditions || {})
? self.getOrCreateCondition(cName)
: undefined;
},
},
context: cfn_parse.CfnParsingContext.CONDITIONS,
parameters: this.parametersToReplace,
});
const cfnCondition = new core.CfnCondition(this.conditionsScope, conditionName, {
expression: cfnParser.parseValue(this.template.Conditions[conditionName]),
});
// ToDo handle renaming of the logical IDs of the conditions
cfnCondition.overrideLogicalId(conditionName);
this.conditions[conditionName] = cfnCondition;
return cfnCondition;
}
private getOrCreateResource(logicalId: string): core.CfnResource {
const ret = this.resources[logicalId];
if (ret) {
return ret;
}
const resourceAttributes: any = this.template.Resources[logicalId];
// fail early for resource attributes we don't support yet
const knownAttributes = [
'Type', 'Properties', 'Condition', 'DependsOn', 'Metadata',
'CreationPolicy', 'UpdatePolicy', 'DeletionPolicy', 'UpdateReplacePolicy',
];
for (const attribute of Object.keys(resourceAttributes)) {
if (!knownAttributes.includes(attribute)) {
throw new Error(`The ${attribute} resource attribute is not supported by cloudformation-include yet. ` +
'Either remove it from the template, or use the CdkInclude class from the core package instead.');
}
}
const self = this;
const finder: cfn_parse.ICfnFinder = {
findCondition(conditionName: string): core.CfnCondition | undefined {
return self.conditions[conditionName];
},
findResource(lId: string): core.CfnResource | undefined {
if (!(lId in (self.template.Resources || {}))) {
return undefined;
}
return self.getOrCreateResource(lId);
},
findRefTarget(elementName: string): core.CfnElement | undefined {
if (elementName in self.parameters) {
return self.parameters[elementName];
}
return this.findResource(elementName);
},
};
const cfnParser = new cfn_parse.CfnParser({
finder,
parameters: this.parametersToReplace,
});
let l1Instance: core.CfnResource;
if (this.nestedStacksToInclude[logicalId]) {
l1Instance = this.createNestedStack(logicalId, cfnParser);
} else {
const l1ClassFqn = cfn_type_to_l1_mapping.lookup(resourceAttributes.Type);
if (l1ClassFqn) {
const options: cfn_parse.FromCloudFormationOptions = {
parser: cfnParser,
};
const [moduleName, ...className] = l1ClassFqn.split('.');
const module = require(moduleName); // eslint-disable-line @typescript-eslint/no-require-imports
const jsClassFromModule = module[className.join('.')];
l1Instance = jsClassFromModule._fromCloudFormation(this, logicalId, resourceAttributes, options);
} else {
l1Instance = new core.CfnResource(this, logicalId, {
type: resourceAttributes.Type,
properties: cfnParser.parseValue(resourceAttributes.Properties),
});
cfnParser.handleAttributes(l1Instance, resourceAttributes, logicalId);
}
}
if (this.preserveLogicalIds) {
// override the logical ID to match the original template
l1Instance.overrideLogicalId(logicalId);
}
this.resources[logicalId] = l1Instance;
return l1Instance;
}
private createNestedStack(nestedStackId: string, cfnParser: cfn_parse.CfnParser): core.CfnResource {
const templateResources = this.template.Resources || {};
const nestedStackAttributes = templateResources[nestedStackId] || {};
if (nestedStackAttributes.Type !== 'AWS::CloudFormation::Stack') {
throw new Error(`Nested Stack with logical ID '${nestedStackId}' is not an AWS::CloudFormation::Stack resource`);
}
if (nestedStackAttributes.CreationPolicy) {
throw new Error('CreationPolicy is not supported by the AWS::CloudFormation::Stack resource');
}
if (nestedStackAttributes.UpdatePolicy) {
throw new Error('UpdatePolicy is not supported by the AWS::CloudFormation::Stack resource');
}
const nestedStackProps = cfnParser.parseValue(nestedStackAttributes.Properties);
const nestedStack = new core.NestedStack(this, nestedStackId, {
parameters: nestedStackProps.Parameters,
notificationArns: nestedStackProps.NotificationArns,
timeout: nestedStackProps.Timeout,
});
// we know this is never undefined for nested stacks
const nestedStackResource: core.CfnResource = nestedStack.nestedStackResource!;
cfnParser.handleAttributes(nestedStackResource, nestedStackAttributes, nestedStackId);
const propStack = this.nestedStacksToInclude[nestedStackId];
const template = new CfnInclude(nestedStack, nestedStackId, {
templateFile: propStack.templateFile,
nestedStacks: propStack.nestedStacks,
});
const includedStack: IncludedNestedStack = { stack: nestedStack, includedTemplate: template };
this.nestedStacks[nestedStackId] = includedStack;
return nestedStackResource;
}
}