jsii 5.9.6-dev.0 → 5.9.7-dev.0

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.
@@ -0,0 +1,1305 @@
1
+ # AWS Cloud Development Kit Library
2
+
3
+ The AWS CDK construct library provides APIs to define your CDK application and add
4
+ CDK constructs to the application.
5
+
6
+ ## Usage
7
+
8
+ ### Upgrade from CDK 1.x
9
+
10
+ When upgrading from CDK 1.x, remove all dependencies to individual CDK packages
11
+ from your dependencies file and follow the rest of the sections.
12
+
13
+ ### Installation
14
+
15
+ To use this package, you need to declare this package and the `constructs` package as
16
+ dependencies.
17
+
18
+ According to the kind of project you are developing:
19
+
20
+ - For projects that are CDK libraries, declare them both under the `devDependencies`
21
+ **and** `peerDependencies` sections.
22
+ - For CDK apps, declare them under the `dependencies` section only.
23
+
24
+ ### Use in your code
25
+
26
+ #### Classic import
27
+
28
+ You can use a classic import to get access to each service namespaces:
29
+
30
+ ```ts
31
+ import { Stack, App, aws_s3 as s3 } from 'aws-cdk-lib';
32
+
33
+ const app = new App();
34
+ const stack = new Stack(app, 'TestStack');
35
+
36
+ new s3.Bucket(stack, 'TestBucket');
37
+ ```
38
+
39
+ #### Barrel import
40
+
41
+ Alternatively, you can use "barrel" imports:
42
+
43
+ ```ts
44
+ import { App, Stack } from 'aws-cdk-lib';
45
+ import { Bucket } from 'aws-cdk-lib/aws-s3';
46
+
47
+ const app = new App();
48
+ const stack = new Stack(app, 'TestStack');
49
+
50
+ new Bucket(stack, 'TestBucket');
51
+ ```
52
+
53
+ <!--BEGIN CORE DOCUMENTATION-->
54
+
55
+ ## Stacks and Stages
56
+
57
+ A `Stack` is the smallest physical unit of deployment, and maps directly onto
58
+ a CloudFormation Stack. You define a Stack by defining a subclass of `Stack`
59
+ -- let's call it `MyStack` -- and instantiating the constructs that make up
60
+ your application in `MyStack`'s constructor. You then instantiate this stack
61
+ one or more times to define different instances of your application. For example,
62
+ you can instantiate it once using few and cheap EC2 instances for testing,
63
+ and once again using more and bigger EC2 instances for production.
64
+
65
+ When your application grows, you may decide that it makes more sense to split it
66
+ out across multiple `Stack` classes. This can happen for a number of reasons:
67
+
68
+ - You could be starting to reach the maximum number of resources allowed in a single
69
+ stack (this is currently 500).
70
+ - You could decide you want to separate out stateful resources and stateless resources
71
+ into separate stacks, so that it becomes easy to tear down and recreate the stacks
72
+ that don't have stateful resources.
73
+ - There could be a single stack with resources (like a VPC) that are shared
74
+ between multiple instances of other stacks containing your applications.
75
+
76
+ As soon as your conceptual application starts to encompass multiple stacks,
77
+ it is convenient to wrap them in another construct that represents your
78
+ logical application. You can then treat that new unit the same way you used
79
+ to be able to treat a single stack: by instantiating it multiple times
80
+ for different instances of your application.
81
+
82
+ You can define a custom subclass of `Stage`, holding one or more
83
+ `Stack`s, to represent a single logical instance of your application.
84
+
85
+ As a final note: `Stack`s are not a unit of reuse. They describe physical
86
+ deployment layouts, and as such are best left to application builders to
87
+ organize their deployments with. If you want to vend a reusable construct,
88
+ define it as a subclasses of `Construct`: the consumers of your construct
89
+ will decide where to place it in their own stacks.
90
+
91
+ ## Stack Synthesizers
92
+
93
+ Each Stack has a *synthesizer*, an object that determines how and where
94
+ the Stack should be synthesized and deployed. The synthesizer controls
95
+ aspects like:
96
+
97
+ - How does the stack reference assets? (Either through CloudFormation
98
+ parameters the CLI supplies, or because the Stack knows a predefined
99
+ location where assets will be uploaded).
100
+ - What roles are used to deploy the stack? These can be bootstrapped
101
+ roles, roles created in some other way, or just the CLI's current
102
+ credentials.
103
+
104
+ The following synthesizers are available:
105
+
106
+ - `DefaultStackSynthesizer`: recommended. Uses predefined asset locations and
107
+ roles created by the modern bootstrap template. Access control is done by
108
+ controlling who can assume the deploy role. This is the default stack
109
+ synthesizer in CDKv2.
110
+ - `LegacyStackSynthesizer`: Uses CloudFormation parameters to communicate
111
+ asset locations, and the CLI's current permissions to deploy stacks. The
112
+ is the default stack synthesizer in CDKv1.
113
+ - `CliCredentialsStackSynthesizer`: Uses predefined asset locations, and the
114
+ CLI's current permissions.
115
+
116
+ Each of these synthesizers takes configuration arguments. To configure
117
+ a stack with a synthesizer, pass it as one of its properties:
118
+
119
+ ```ts
120
+ new MyStack(app, 'MyStack', {
121
+ synthesizer: new DefaultStackSynthesizer({
122
+ fileAssetsBucketName: 'my-orgs-asset-bucket',
123
+ }),
124
+ });
125
+ ```
126
+
127
+ For more information on bootstrapping accounts and customizing synthesis,
128
+ see [Bootstrapping in the CDK Developer Guide](https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html).
129
+
130
+ ## Nested Stacks
131
+
132
+ [Nested stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html) are stacks created as part of other stacks. You create a nested stack within another stack by using the `NestedStack` construct.
133
+
134
+ As your infrastructure grows, common patterns can emerge in which you declare the same components in multiple templates. You can separate out these common components and create dedicated templates for them. Then use the resource in your template to reference other templates, creating nested stacks.
135
+
136
+ For example, assume that you have a load balancer configuration that you use for most of your stacks. Instead of copying and pasting the same configurations into your templates, you can create a dedicated template for the load balancer. Then, you just use the resource to reference that template from within other templates.
137
+
138
+ The following example will define a single top-level stack that contains two nested stacks: each one with a single Amazon S3 bucket:
139
+
140
+ ```ts
141
+ class MyNestedStack extends cfn.NestedStack {
142
+ constructor(scope: Construct, id: string, props?: cfn.NestedStackProps) {
143
+ super(scope, id, props);
144
+
145
+ new s3.Bucket(this, 'NestedBucket');
146
+ }
147
+ }
148
+
149
+ class MyParentStack extends Stack {
150
+ constructor(scope: Construct, id: string, props?: StackProps) {
151
+ super(scope, id, props);
152
+
153
+ new MyNestedStack(this, 'Nested1');
154
+ new MyNestedStack(this, 'Nested2');
155
+ }
156
+ }
157
+ ```
158
+
159
+ Resources references across nested/parent boundaries (even with multiple levels of nesting) will be wired by the AWS CDK
160
+ through CloudFormation parameters and outputs. When a resource from a parent stack is referenced by a nested stack,
161
+ a CloudFormation parameter will automatically be added to the nested stack and assigned from the parent; when a resource
162
+ from a nested stack is referenced by a parent stack, a CloudFormation output will be automatically be added to the
163
+ nested stack and referenced using `Fn::GetAtt "Outputs.Xxx"` from the parent.
164
+
165
+ Nested stacks also support the use of Docker image and file assets.
166
+
167
+ ## Accessing resources in a different stack
168
+
169
+ You can access resources in a different stack, as long as they are in the
170
+ same account and AWS Region (see [next section](#accessing-resources-in-a-different-stack-and-region) for an exception).
171
+ The following example defines the stack `stack1`,
172
+ which defines an Amazon S3 bucket. Then it defines a second stack, `stack2`,
173
+ which takes the bucket from stack1 as a constructor property.
174
+
175
+ ```ts
176
+ const prod = { account: '123456789012', region: 'us-east-1' };
177
+
178
+ const stack1 = new StackThatProvidesABucket(app, 'Stack1' , { env: prod });
179
+
180
+ // stack2 will take a property { bucket: IBucket }
181
+ const stack2 = new StackThatExpectsABucket(app, 'Stack2', {
182
+ bucket: stack1.bucket,
183
+ env: prod
184
+ });
185
+ ```
186
+
187
+ If the AWS CDK determines that the resource is in the same account and
188
+ Region, but in a different stack, it automatically synthesizes AWS
189
+ CloudFormation
190
+ [Exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html)
191
+ in the producing stack and an
192
+ [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html)
193
+ in the consuming stack to transfer that information from one stack to the
194
+ other.
195
+
196
+ ## Accessing resources in a different stack and region
197
+
198
+ > **This feature is currently experimental**
199
+
200
+ You can enable the Stack property `crossRegionReferences`
201
+ in order to access resources in a different stack _and_ region. With this feature flag
202
+ enabled it is possible to do something like creating a CloudFront distribution in `us-east-2` and
203
+ an ACM certificate in `us-east-1`.
204
+
205
+ ```ts
206
+ const stack1 = new Stack(app, 'Stack1', {
207
+ env: {
208
+ region: 'us-east-1',
209
+ },
210
+ crossRegionReferences: true,
211
+ });
212
+ const cert = new acm.Certificate(stack1, 'Cert', {
213
+ domainName: '*.example.com',
214
+ validation: acm.CertificateValidation.fromDns(route53.PublicHostedZone.fromHostedZoneId(stack1, 'Zone', 'Z0329774B51CGXTDQV3X')),
215
+ });
216
+
217
+ const stack2 = new Stack(app, 'Stack2', {
218
+ env: {
219
+ region: 'us-east-2',
220
+ },
221
+ crossRegionReferences: true,
222
+ });
223
+ new cloudfront.Distribution(stack2, 'Distribution', {
224
+ defaultBehavior: {
225
+ origin: new origins.HttpOrigin('example.com'),
226
+ },
227
+ domainNames: ['dev.example.com'],
228
+ certificate: cert,
229
+ });
230
+ ```
231
+
232
+ When the AWS CDK determines that the resource is in a different stack _and_ is in a different
233
+ region, it will "export" the value by creating a custom resource in the producing stack which
234
+ creates SSM Parameters in the consuming region for each exported value. The parameters will be
235
+ created with the name '/cdk/exports/${consumingStackName}/${export-name}'.
236
+ In order to "import" the exports into the consuming stack a [SSM Dynamic reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#dynamic-references-ssm)
237
+ is used to reference the SSM parameter which was created.
238
+
239
+ In order to mimic strong references, a Custom Resource is also created in the consuming
240
+ stack which marks the SSM parameters as being "imported". When a parameter has been successfully
241
+ imported, the producing stack cannot update the value.
242
+
243
+ See the [adr](https://github.com/aws/aws-cdk/blob/main/packages/@aws-cdk/core/adr/cross-region-stack-references)
244
+ for more details on this feature.
245
+
246
+ ### Removing automatic cross-stack references
247
+
248
+ The automatic references created by CDK when you use resources across stacks
249
+ are convenient, but may block your deployments if you want to remove the
250
+ resources that are referenced in this way. You will see an error like:
251
+
252
+ ```text
253
+ Export Stack1:ExportsOutputFnGetAtt-****** cannot be deleted as it is in use by Stack1
254
+ ```
255
+
256
+ Let's say there is a Bucket in the `stack1`, and the `stack2` references its
257
+ `bucket.bucketName`. You now want to remove the bucket and run into the error above.
258
+
259
+ It's not safe to remove `stack1.bucket` while `stack2` is still using it, so
260
+ unblocking yourself from this is a two-step process. This is how it works:
261
+
262
+ DEPLOYMENT 1: break the relationship
263
+
264
+ - Make sure `stack2` no longer references `bucket.bucketName` (maybe the consumer
265
+ stack now uses its own bucket, or it writes to an AWS DynamoDB table, or maybe you just
266
+ remove the Lambda Function altogether).
267
+ - In the `stack1` class, call `this.exportValue(this.bucket.bucketName)`. This
268
+ will make sure the CloudFormation Export continues to exist while the relationship
269
+ between the two stacks is being broken.
270
+ - Deploy (this will effectively only change the `stack2`, but it's safe to deploy both).
271
+
272
+ DEPLOYMENT 2: remove the resource
273
+
274
+ - You are now free to remove the `bucket` resource from `stack1`.
275
+ - Don't forget to remove the `exportValue()` call as well.
276
+ - Deploy again (this time only the `stack1` will be changed -- the bucket will be deleted).
277
+
278
+ ## Durations
279
+
280
+ To make specifications of time intervals unambiguous, a single class called
281
+ `Duration` is used throughout the AWS Construct Library by all constructs
282
+ that that take a time interval as a parameter (be it for a timeout, a
283
+ rate, or something else).
284
+
285
+ An instance of Duration is constructed by using one of the static factory
286
+ methods on it:
287
+
288
+ ```ts
289
+ Duration.seconds(300) // 5 minutes
290
+ Duration.minutes(5) // 5 minutes
291
+ Duration.hours(1) // 1 hour
292
+ Duration.days(7) // 7 days
293
+ Duration.parse('PT5M') // 5 minutes
294
+ ```
295
+
296
+ Durations can be added or subtracted together:
297
+
298
+ ```ts
299
+ Duration.minutes(1).plus(Duration.seconds(60)); // 2 minutes
300
+ Duration.minutes(5).minus(Duration.seconds(10)); // 290 secondes
301
+ ```
302
+
303
+ ## Size (Digital Information Quantity)
304
+
305
+ To make specification of digital storage quantities unambiguous, a class called
306
+ `Size` is available.
307
+
308
+ An instance of `Size` is initialized through one of its static factory methods:
309
+
310
+ ```ts
311
+ Size.kibibytes(200) // 200 KiB
312
+ Size.mebibytes(5) // 5 MiB
313
+ Size.gibibytes(40) // 40 GiB
314
+ Size.tebibytes(200) // 200 TiB
315
+ Size.pebibytes(3) // 3 PiB
316
+ ```
317
+
318
+ Instances of `Size` created with one of the units can be converted into others.
319
+ By default, conversion to a higher unit will fail if the conversion does not produce
320
+ a whole number. This can be overridden by unsetting `integral` property.
321
+
322
+ ```ts
323
+ Size.mebibytes(2).toKibibytes() // yields 2048
324
+ Size.kibibytes(2050).toMebibytes({ rounding: SizeRoundingBehavior.FLOOR }) // yields 2
325
+ ```
326
+
327
+ ## Secrets
328
+
329
+ To help avoid accidental storage of secrets as plain text, we use the `SecretValue` type to
330
+ represent secrets. Any construct that takes a value that should be a secret (such as
331
+ a password or an access key) will take a parameter of type `SecretValue`.
332
+
333
+ The best practice is to store secrets in AWS Secrets Manager and reference them using `SecretValue.secretsManager`:
334
+
335
+ ```ts
336
+ const secret = SecretValue.secretsManager('secretId', {
337
+ jsonField: 'password', // optional: key of a JSON field to retrieve (defaults to all content),
338
+ versionId: 'id', // optional: id of the version (default AWSCURRENT)
339
+ versionStage: 'stage', // optional: version stage name (default AWSCURRENT)
340
+ });
341
+ ```
342
+
343
+ Using AWS Secrets Manager is the recommended way to reference secrets in a CDK app.
344
+ `SecretValue` also supports the following secret sources:
345
+
346
+ - `SecretValue.unsafePlainText(secret)`: stores the secret as plain text in your app and the resulting template (not recommended).
347
+ - `SecretValue.secretsManager(secret)`: refers to a secret stored in Secrets Manager
348
+ - `SecretValue.ssmSecure(param, version)`: refers to a secret stored as a SecureString in the SSM
349
+ Parameter Store. If you don't specify the exact version, AWS CloudFormation uses the latest
350
+ version of the parameter.
351
+ - `SecretValue.cfnParameter(param)`: refers to a secret passed through a CloudFormation parameter (must have `NoEcho: true`).
352
+ - `SecretValue.cfnDynamicReference(dynref)`: refers to a secret described by a CloudFormation dynamic reference (used by `ssmSecure` and `secretsManager`).
353
+ - `SecretValue.resourceAttribute(attr)`: refers to a secret returned from a CloudFormation resource creation.
354
+
355
+ `SecretValue`s should only be passed to constructs that accept properties of type
356
+ `SecretValue`. These constructs are written to ensure your secrets will not be
357
+ exposed where they shouldn't be. If you try to use a `SecretValue` in a
358
+ different location, an error about unsafe secret usage will be thrown at
359
+ synthesis time.
360
+
361
+ If you rotate the secret's value in Secrets Manager, you must also change at
362
+ least one property on the resource where you are using the secret, to force
363
+ CloudFormation to re-read the secret.
364
+
365
+ `SecretValue.ssmSecure()` is only supported for a limited set of resources.
366
+ [Click here for a list of supported resources and properties](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#template-parameters-dynamic-patterns-resources).
367
+
368
+ ## ARN manipulation
369
+
370
+ Sometimes you will need to put together or pick apart Amazon Resource Names
371
+ (ARNs). The functions `stack.formatArn()` and `stack.parseArn()` exist for
372
+ this purpose.
373
+
374
+ `formatArn()` can be used to build an ARN from components. It will automatically
375
+ use the region and account of the stack you're calling it on:
376
+
377
+ ```ts
378
+ declare const stack: Stack;
379
+
380
+ // Builds "arn:<PARTITION>:lambda:<REGION>:<ACCOUNT>:function:MyFunction"
381
+ stack.formatArn({
382
+ service: 'lambda',
383
+ resource: 'function',
384
+ sep: ':',
385
+ resourceName: 'MyFunction'
386
+ });
387
+ ```
388
+
389
+ `parseArn()` can be used to get a single component from an ARN. `parseArn()`
390
+ will correctly deal with both literal ARNs and deploy-time values (tokens),
391
+ but in case of a deploy-time value be aware that the result will be another
392
+ deploy-time value which cannot be inspected in the CDK application.
393
+
394
+ ```ts
395
+ declare const stack: Stack;
396
+
397
+ // Extracts the function name out of an AWS Lambda Function ARN
398
+ const arnComponents = stack.parseArn(arn, ':');
399
+ const functionName = arnComponents.resourceName;
400
+ ```
401
+
402
+ Note that depending on the service, the resource separator can be either
403
+ `:` or `/`, and the resource name can be either the 6th or 7th
404
+ component in the ARN. When using these functions, you will need to know
405
+ the format of the ARN you are dealing with.
406
+
407
+ For an exhaustive list of ARN formats used in AWS, see [AWS ARNs and
408
+ Namespaces](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html)
409
+ in the AWS General Reference.
410
+
411
+ ## Dependencies
412
+
413
+ ### Construct Dependencies
414
+
415
+ Sometimes AWS resources depend on other resources, and the creation of one
416
+ resource must be completed before the next one can be started.
417
+
418
+ In general, CloudFormation will correctly infer the dependency relationship
419
+ between resources based on the property values that are used. In the cases where
420
+ it doesn't, the AWS Construct Library will add the dependency relationship for
421
+ you.
422
+
423
+ If you need to add an ordering dependency that is not automatically inferred,
424
+ you do so by adding a dependency relationship using
425
+ `constructA.node.addDependency(constructB)`. This will add a dependency
426
+ relationship between all resources in the scope of `constructA` and all
427
+ resources in the scope of `constructB`.
428
+
429
+ If you want a single object to represent a set of constructs that are not
430
+ necessarily in the same scope, you can use a `DependencyGroup`. The
431
+ following creates a single object that represents a dependency on two
432
+ constructs, `constructB` and `constructC`:
433
+
434
+ ```ts
435
+ // Declare the dependable object
436
+ const bAndC = new DependencyGroup();
437
+ bAndC.add(constructB);
438
+ bAndC.add(constructC);
439
+
440
+ // Take the dependency
441
+ constructA.node.addDependency(bAndC);
442
+ ```
443
+
444
+ ### Stack Dependencies
445
+
446
+ Two different stack instances can have a dependency on one another. This
447
+ happens when an resource from one stack is referenced in another stack. In
448
+ that case, CDK records the cross-stack referencing of resources,
449
+ automatically produces the right CloudFormation primitives, and adds a
450
+ dependency between the two stacks. You can also manually add a dependency
451
+ between two stacks by using the `stackA.addDependency(stackB)` method.
452
+
453
+ A stack dependency has the following implications:
454
+
455
+ - Cyclic dependencies are not allowed, so if `stackA` is using resources from
456
+ `stackB`, the reverse is not possible anymore.
457
+ - Stacks with dependencies between them are treated specially by the CDK
458
+ toolkit:
459
+ - If `stackA` depends on `stackB`, running `cdk deploy stackA` will also
460
+ automatically deploy `stackB`.
461
+ - `stackB`'s deployment will be performed *before* `stackA`'s deployment.
462
+
463
+ ### CfnResource Dependencies
464
+
465
+ To make declaring dependencies between `CfnResource` objects easier, you can declare dependencies from one `CfnResource` object on another by using the `cfnResource1.addDependency(cfnResource2)` method. This method will work for resources both within the same stack and across stacks as it detects the relative location of the two resources and adds the dependency either to the resource or between the relevant stacks, as appropriate. If more complex logic is in needed, you can similarly remove, replace, or view dependencies between `CfnResource` objects with the `CfnResource` `removeDependency`, `replaceDependency`, and `obtainDependencies` methods, respectively.
466
+
467
+ ## Custom Resources
468
+
469
+ Custom Resources are CloudFormation resources that are implemented by arbitrary
470
+ user code. They can do arbitrary lookups or modifications during a
471
+ CloudFormation deployment.
472
+
473
+ Custom resources are backed by *custom resource providers*. Commonly, these are
474
+ Lambda Functions that are deployed in the same deployment as the one that
475
+ defines the custom resource itself, but they can also be backed by Lambda
476
+ Functions deployed previously, or code responding to SNS Topic events running on
477
+ EC2 instances in a completely different account. For more information on custom
478
+ resource providers, see the next section.
479
+
480
+ Once you have a provider, each definition of a `CustomResource` construct
481
+ represents one invocation. A single provider can be used for the implementation
482
+ of arbitrarily many custom resource definitions. A single definition looks like
483
+ this:
484
+
485
+ ```ts
486
+ new CustomResource(this, 'MyMagicalResource', {
487
+ resourceType: 'Custom::MyCustomResource', // must start with 'Custom::'
488
+
489
+ // the resource properties
490
+ properties: {
491
+ Property1: 'foo',
492
+ Property2: 'bar'
493
+ },
494
+
495
+ // the ARN of the provider (SNS/Lambda) which handles
496
+ // CREATE, UPDATE or DELETE events for this resource type
497
+ // see next section for details
498
+ serviceToken: 'ARN'
499
+ });
500
+ ```
501
+
502
+ ### Custom Resource Providers
503
+
504
+ Custom resources are backed by a **custom resource provider** which can be
505
+ implemented in one of the following ways. The following table compares the
506
+ various provider types (ordered from low-level to high-level):
507
+
508
+ | Provider | Compute Type | Error Handling | Submit to CloudFormation | Max Timeout | Language | Footprint |
509
+ |----------------------------------------------------------------------|:------------:|:--------------:|:------------------------:|:---------------:|:--------:|:---------:|
510
+ | [sns.Topic](#amazon-sns-topic) | Self-managed | Manual | Manual | Unlimited | Any | Depends |
511
+ | [lambda.Function](#aws-lambda-function) | AWS Lambda | Manual | Manual | 15min | Any | Small |
512
+ | [core.CustomResourceProvider](#the-corecustomresourceprovider-class) | AWS Lambda | Auto | Auto | 15min | Node.js | Small |
513
+ | [custom-resources.Provider](#the-custom-resource-provider-framework) | AWS Lambda | Auto | Auto | Unlimited Async | Any | Large |
514
+
515
+ Legend:
516
+
517
+ - **Compute type**: which type of compute can be used to execute the handler.
518
+ - **Error Handling**: whether errors thrown by handler code are automatically
519
+ trapped and a FAILED response is submitted to CloudFormation. If this is
520
+ "Manual", developers must take care of trapping errors. Otherwise, events
521
+ could cause stacks to hang.
522
+ - **Submit to CloudFormation**: whether the framework takes care of submitting
523
+ SUCCESS/FAILED responses to CloudFormation through the event's response URL.
524
+ - **Max Timeout**: maximum allows/possible timeout.
525
+ - **Language**: which programming languages can be used to implement handlers.
526
+ - **Footprint**: how many resources are used by the provider framework itself.
527
+
528
+ **A NOTE ABOUT SINGLETONS**
529
+
530
+ When defining resources for a custom resource provider, you will likely want to
531
+ define them as a *stack singleton* so that only a single instance of the
532
+ provider is created in your stack and which is used by all custom resources of
533
+ that type.
534
+
535
+ Here is a basic pattern for defining stack singletons in the CDK. The following
536
+ examples ensures that only a single SNS topic is defined:
537
+
538
+ ```ts
539
+ function getOrCreate(scope: Construct): sns.Topic {
540
+ const stack = Stack.of(scope);
541
+ const uniqueid = 'GloballyUniqueIdForSingleton'; // For example, a UUID from `uuidgen`
542
+ const existing = stack.node.tryFindChild(uniqueid);
543
+ if (existing) {
544
+ return existing as sns.Topic;
545
+ }
546
+ return new sns.Topic(stack, uniqueid);
547
+ }
548
+ ```
549
+
550
+ #### Amazon SNS Topic
551
+
552
+ Every time a resource event occurs (CREATE/UPDATE/DELETE), an SNS notification
553
+ is sent to the SNS topic. Users must process these notifications (e.g. through a
554
+ fleet of worker hosts) and submit success/failure responses to the
555
+ CloudFormation service.
556
+
557
+ > You only need to use this type of provider if your custom resource cannot run on AWS Lambda, for reasons other than the 15
558
+ > minute timeout. If you are considering using this type of provider because you want to write a custom resource provider that may need
559
+ > to wait for more than 15 minutes for the API calls to stabilize, have a look at the [`custom-resources`](#the-custom-resource-provider-framework) module first.
560
+ >
561
+ > Refer to the [CloudFormation Custom Resource documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) for information on the contract your custom resource needs to adhere to.
562
+
563
+ Set `serviceToken` to `topic.topicArn` in order to use this provider:
564
+
565
+ ```ts
566
+ const topic = new sns.Topic(this, 'MyProvider');
567
+
568
+ new CustomResource(this, 'MyResource', {
569
+ serviceToken: topic.topicArn
570
+ });
571
+ ```
572
+
573
+ #### AWS Lambda Function
574
+
575
+ An AWS lambda function is called *directly* by CloudFormation for all resource
576
+ events. The handler must take care of explicitly submitting a success/failure
577
+ response to the CloudFormation service and handle various error cases.
578
+
579
+ > **We do not recommend you use this provider type.** The CDK has wrappers around Lambda Functions that make them easier to work with.
580
+ >
581
+ > If you do want to use this provider, refer to the [CloudFormation Custom Resource documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) for information on the contract your custom resource needs to adhere to.
582
+
583
+ Set `serviceToken` to `lambda.functionArn` to use this provider:
584
+
585
+ ```ts
586
+ const fn = new lambda.Function(this, 'MyProvider', functionProps);
587
+
588
+ new CustomResource(this, 'MyResource', {
589
+ serviceToken: fn.functionArn,
590
+ });
591
+ ```
592
+
593
+ #### The `core.CustomResourceProvider` class
594
+
595
+ The class [`@aws-cdk/core.CustomResourceProvider`] offers a basic low-level
596
+ framework designed to implement simple and slim custom resource providers. It
597
+ currently only supports Node.js-based user handlers, represents permissions as raw
598
+ JSON blobs instead of `iam.PolicyStatement` objects, and it does not have
599
+ support for asynchronous waiting (handler cannot exceed the 15min lambda
600
+ timeout).
601
+
602
+ [`@aws-cdk/core.CustomResourceProvider`]: https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CustomResourceProvider.html
603
+
604
+ > **As an application builder, we do not recommend you use this provider type.** This provider exists purely for custom resources that are part of the AWS Construct Library.
605
+ >
606
+ > The [`custom-resources`](#the-custom-resource-provider-framework) provider is more convenient to work with and more fully-featured.
607
+
608
+ The provider has a built-in singleton method which uses the resource type as a
609
+ stack-unique identifier and returns the service token:
610
+
611
+ ```ts
612
+ const serviceToken = CustomResourceProvider.getOrCreate(this, 'Custom::MyCustomResourceType', {
613
+ codeDirectory: `${__dirname}/my-handler`,
614
+ runtime: CustomResourceProviderRuntime.NODEJS_14_X,
615
+ description: "Lambda function created by the custom resource provider",
616
+ });
617
+
618
+ new CustomResource(this, 'MyResource', {
619
+ resourceType: 'Custom::MyCustomResourceType',
620
+ serviceToken: serviceToken
621
+ });
622
+ ```
623
+
624
+ The directory (`my-handler` in the above example) must include an `index.js` file. It cannot import
625
+ external dependencies or files outside this directory. It must export an async
626
+ function named `handler`. This function accepts the CloudFormation resource
627
+ event object and returns an object with the following structure:
628
+
629
+ ```js
630
+ exports.handler = async function(event) {
631
+ const id = event.PhysicalResourceId; // only for "Update" and "Delete"
632
+ const props = event.ResourceProperties;
633
+ const oldProps = event.OldResourceProperties; // only for "Update"s
634
+
635
+ switch (event.RequestType) {
636
+ case "Create":
637
+ // ...
638
+
639
+ case "Update":
640
+ // ...
641
+
642
+ // if an error is thrown, a FAILED response will be submitted to CFN
643
+ throw new Error('Failed!');
644
+
645
+ case "Delete":
646
+ // ...
647
+ }
648
+
649
+ return {
650
+ // (optional) the value resolved from `resource.ref`
651
+ // defaults to "event.PhysicalResourceId" or "event.RequestId"
652
+ PhysicalResourceId: "REF",
653
+
654
+ // (optional) calling `resource.getAtt("Att1")` on the custom resource in the CDK app
655
+ // will return the value "BAR".
656
+ Data: {
657
+ Att1: "BAR",
658
+ Att2: "BAZ"
659
+ },
660
+
661
+ // (optional) user-visible message
662
+ Reason: "User-visible message",
663
+
664
+ // (optional) hides values from the console
665
+ NoEcho: true
666
+ };
667
+ }
668
+ ```
669
+
670
+ Here is an complete example of a custom resource that summarizes two numbers:
671
+
672
+ `sum-handler/index.js`:
673
+
674
+ ```js
675
+ exports.handler = async (e) => {
676
+ return {
677
+ Data: {
678
+ Result: e.ResourceProperties.lhs + e.ResourceProperties.rhs,
679
+ },
680
+ };
681
+ };
682
+ ```
683
+
684
+ `sum.ts`:
685
+
686
+ ```ts nofixture
687
+ import {
688
+ Construct,
689
+ CustomResource,
690
+ CustomResourceProvider,
691
+ CustomResourceProviderRuntime,
692
+ Token,
693
+ } from '@aws-cdk/core';
694
+
695
+ export interface SumProps {
696
+ readonly lhs: number;
697
+ readonly rhs: number;
698
+ }
699
+
700
+ export class Sum extends Construct {
701
+ public readonly result: number;
702
+
703
+ constructor(scope: Construct, id: string, props: SumProps) {
704
+ super(scope, id);
705
+
706
+ const resourceType = 'Custom::Sum';
707
+ const serviceToken = CustomResourceProvider.getOrCreate(this, resourceType, {
708
+ codeDirectory: `${__dirname}/sum-handler`,
709
+ runtime: CustomResourceProviderRuntime.NODEJS_14_X,
710
+ });
711
+
712
+ const resource = new CustomResource(this, 'Resource', {
713
+ resourceType: resourceType,
714
+ serviceToken: serviceToken,
715
+ properties: {
716
+ lhs: props.lhs,
717
+ rhs: props.rhs
718
+ }
719
+ });
720
+
721
+ this.result = Token.asNumber(resource.getAtt('Result'));
722
+ }
723
+ }
724
+ ```
725
+
726
+ Usage will look like this:
727
+
728
+ ```ts fixture=README-custom-resource-provider
729
+ const sum = new Sum(this, 'MySum', { lhs: 40, rhs: 2 });
730
+ new CfnOutput(this, 'Result', { value: Token.asString(sum.result) });
731
+ ```
732
+
733
+ To access the ARN of the provider's AWS Lambda function role, use the `getOrCreateProvider()`
734
+ built-in singleton method:
735
+
736
+ ```ts
737
+ const provider = CustomResourceProvider.getOrCreateProvider(this, 'Custom::MyCustomResourceType', {
738
+ codeDirectory: `${__dirname}/my-handler`,
739
+ runtime: CustomResourceProviderRuntime.NODEJS_14_X,
740
+ });
741
+
742
+ const roleArn = provider.roleArn;
743
+ ```
744
+
745
+ This role ARN can then be used in resource-based IAM policies.
746
+
747
+ To add IAM policy statements to this role, use `addToRolePolicy()`:
748
+
749
+ ```ts
750
+ const provider = CustomResourceProvider.getOrCreateProvider(this, 'Custom::MyCustomResourceType', {
751
+ codeDirectory: `${__dirname}/my-handler`,
752
+ runtime: CustomResourceProviderRuntime.NODEJS_14_X,
753
+ });
754
+ provider.addToRolePolicy({
755
+ Effect: 'Allow',
756
+ Action: 's3:GetObject',
757
+ Resource: '*',
758
+ })
759
+ ```
760
+
761
+ Note that `addToRolePolicy()` uses direct IAM JSON policy blobs, *not* a
762
+ `iam.PolicyStatement` object like you will see in the rest of the CDK.
763
+
764
+ #### The Custom Resource Provider Framework
765
+
766
+ The [`@aws-cdk/custom-resources`] module includes an advanced framework for
767
+ implementing custom resource providers.
768
+
769
+ [`@aws-cdk/custom-resources`]: https://docs.aws.amazon.com/cdk/api/latest/docs/custom-resources-readme.html
770
+
771
+ Handlers are implemented as AWS Lambda functions, which means that they can be
772
+ implemented in any Lambda-supported runtime. Furthermore, this provider has an
773
+ asynchronous mode, which means that users can provide an `isComplete` lambda
774
+ function which is called periodically until the operation is complete. This
775
+ allows implementing providers that can take up to two hours to stabilize.
776
+
777
+ Set `serviceToken` to `provider.serviceToken` to use this type of provider:
778
+
779
+ ```ts
780
+ const provider = new customresources.Provider(this, 'MyProvider', {
781
+ onEventHandler,
782
+ isCompleteHandler, // optional async waiter
783
+ });
784
+
785
+ new CustomResource(this, 'MyResource', {
786
+ serviceToken: provider.serviceToken
787
+ });
788
+ ```
789
+
790
+ See the [documentation](https://docs.aws.amazon.com/cdk/api/latest/docs/custom-resources-readme.html) for more details.
791
+
792
+ ## AWS CloudFormation features
793
+
794
+ A CDK stack synthesizes to an AWS CloudFormation Template. This section
795
+ explains how this module allows users to access low-level CloudFormation
796
+ features when needed.
797
+
798
+ ### Stack Outputs
799
+
800
+ CloudFormation [stack outputs][cfn-stack-output] and exports are created using
801
+ the `CfnOutput` class:
802
+
803
+ ```ts
804
+ new CfnOutput(this, 'OutputName', {
805
+ value: myBucket.bucketName,
806
+ description: 'The name of an S3 bucket', // Optional
807
+ exportName: 'TheAwesomeBucket', // Registers a CloudFormation export named "TheAwesomeBucket"
808
+ });
809
+ ```
810
+
811
+ [cfn-stack-output]: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html
812
+
813
+ ### Parameters
814
+
815
+ CloudFormation templates support the use of [Parameters][cfn-parameters] to
816
+ customize a template. They enable CloudFormation users to input custom values to
817
+ a template each time a stack is created or updated. While the CDK design
818
+ philosophy favors using build-time parameterization, users may need to use
819
+ CloudFormation in a number of cases (for example, when migrating an existing
820
+ stack to the AWS CDK).
821
+
822
+ Template parameters can be added to a stack by using the `CfnParameter` class:
823
+
824
+ ```ts
825
+ new CfnParameter(this, 'MyParameter', {
826
+ type: 'Number',
827
+ default: 1337,
828
+ // See the API reference for more configuration props
829
+ });
830
+ ```
831
+
832
+ The value of parameters can then be obtained using one of the `value` methods.
833
+ As parameters are only resolved at deployment time, the values obtained are
834
+ placeholder tokens for the real value (`Token.isUnresolved()` would return `true`
835
+ for those):
836
+
837
+ ```ts
838
+ const param = new CfnParameter(this, 'ParameterName', { /* config */ });
839
+
840
+ // If the parameter is a String
841
+ param.valueAsString;
842
+
843
+ // If the parameter is a Number
844
+ param.valueAsNumber;
845
+
846
+ // If the parameter is a List
847
+ param.valueAsList;
848
+ ```
849
+
850
+ [cfn-parameters]: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html
851
+
852
+ ### Pseudo Parameters
853
+
854
+ CloudFormation supports a number of [pseudo parameters][cfn-pseudo-params],
855
+ which resolve to useful values at deployment time. CloudFormation pseudo
856
+ parameters can be obtained from static members of the `Aws` class.
857
+
858
+ It is generally recommended to access pseudo parameters from the scope's `stack`
859
+ instead, which guarantees the values produced are qualifying the designated
860
+ stack, which is essential in cases where resources are shared cross-stack:
861
+
862
+ ```ts
863
+ // "this" is the current construct
864
+ const stack = Stack.of(this);
865
+
866
+ stack.account; // Returns the AWS::AccountId for this stack (or the literal value if known)
867
+ stack.region; // Returns the AWS::Region for this stack (or the literal value if known)
868
+ stack.partition; // Returns the AWS::Partition for this stack (or the literal value if known)
869
+ ```
870
+
871
+ [cfn-pseudo-params]: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/pseudo-parameter-reference.html
872
+
873
+ ### Resource Options
874
+
875
+ CloudFormation resources can also specify [resource
876
+ attributes][cfn-resource-attributes]. The `CfnResource` class allows
877
+ accessing those through the `cfnOptions` property:
878
+
879
+ ```ts
880
+ const rawBucket = new s3.CfnBucket(this, 'Bucket', { /* ... */ });
881
+ // -or-
882
+ const rawBucketAlt = myBucket.node.defaultChild as s3.CfnBucket;
883
+
884
+ // then
885
+ rawBucket.cfnOptions.condition = new CfnCondition(this, 'EnableBucket', { /* ... */ });
886
+ rawBucket.cfnOptions.metadata = {
887
+ metadataKey: 'MetadataValue',
888
+ };
889
+ ```
890
+
891
+ Resource dependencies (the `DependsOn` attribute) is modified using the
892
+ `cfnResource.addDependency` method:
893
+
894
+ ```ts
895
+ const resourceA = new CfnResource(this, 'ResourceA', resourceProps);
896
+ const resourceB = new CfnResource(this, 'ResourceB', resourceProps);
897
+
898
+ resourceB.addDependency(resourceA);
899
+ ```
900
+
901
+ [cfn-resource-attributes]: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-product-attribute-reference.html
902
+
903
+ #### CreationPolicy
904
+
905
+ Some resources support a [CreationPolicy][creation-policy] to be specified as a CfnOption.
906
+
907
+ The creation policy is invoked only when AWS CloudFormation creates the associated resource. Currently, the only AWS CloudFormation resources that support creation policies are `CfnAutoScalingGroup`, `CfnInstance`, `CfnWaitCondition` and `CfnFleet`.
908
+
909
+ The `CfnFleet` resource from the `aws-appstream` module supports specifying `startFleet` as
910
+ a property of the creationPolicy on the resource options. Setting it to true will make AWS CloudFormation wait until the fleet is started before continuing with the creation of
911
+ resources that depend on the fleet resource.
912
+
913
+ ```ts
914
+ const fleet = new CfnFleet(stack, 'Fleet', {
915
+ instanceType: 'stream.standard.small',
916
+ name: 'Fleet',
917
+ computeCapacity: {
918
+ desiredInstances: 1,
919
+ },
920
+ imageName: 'AppStream-AmazonLinux2-09-21-2022',
921
+ });
922
+ fleet.cfnOptions.creationPolicy = {
923
+ startFleet: true,
924
+ };
925
+ ```
926
+
927
+ The properties passed to the level 2 constructs `AutoScalingGroup` and `Instance` from the
928
+ `aws-ec2` module abstract what is passed into the `CfnOption` properties `resourceSignal` and
929
+ `autoScalingCreationPolicy`, but when using level 1 constructs you can specify these yourself.
930
+
931
+ The CfnWaitCondition resource from the `aws-cloudformation` module suppports the `resourceSignal`.
932
+ The format of the timeout is `PT#H#M#S`. In the example below AWS Cloudformation will wait for
933
+ 3 success signals to occur within 15 minutes before the status of the resource will be set to
934
+ `CREATE_COMPLETE`.
935
+
936
+ ```ts
937
+ resource.cfnOptions.resourceSignal = {
938
+ count: 3,
939
+ timeout: 'PR15M',
940
+ }
941
+ ```
942
+
943
+ [creation-policy]: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-creationpolicy.html
944
+
945
+ ### Intrinsic Functions and Condition Expressions
946
+
947
+ CloudFormation supports [intrinsic functions][cfn-intrinsics]. These functions
948
+ can be accessed from the `Fn` class, which provides type-safe methods for each
949
+ intrinsic function as well as condition expressions:
950
+
951
+ ```ts
952
+ declare const myObjectOrArray: any;
953
+ declare const myArray: any;
954
+
955
+ // To use Fn::Base64
956
+ Fn.base64('SGVsbG8gQ0RLIQo=');
957
+
958
+ // To compose condition expressions:
959
+ const environmentParameter = new CfnParameter(this, 'Environment');
960
+ Fn.conditionAnd(
961
+ // The "Environment" CloudFormation template parameter evaluates to "Production"
962
+ Fn.conditionEquals('Production', environmentParameter),
963
+ // The AWS::Region pseudo-parameter value is NOT equal to "us-east-1"
964
+ Fn.conditionNot(Fn.conditionEquals('us-east-1', Aws.REGION)),
965
+ );
966
+
967
+ // To use Fn::ToJsonString
968
+ Fn.toJsonString(myObjectOrArray);
969
+
970
+ // To use Fn::Length
971
+ Fn.len(Fn.split(',', myArray));
972
+ ```
973
+
974
+ When working with deploy-time values (those for which `Token.isUnresolved`
975
+ returns `true`), idiomatic conditionals from the programming language cannot be
976
+ used (the value will not be known until deployment time). When conditional logic
977
+ needs to be expressed with un-resolved values, it is necessary to use
978
+ CloudFormation conditions by means of the `CfnCondition` class:
979
+
980
+ ```ts
981
+ const environmentParameter = new CfnParameter(this, 'Environment');
982
+ const isProd = new CfnCondition(this, 'IsProduction', {
983
+ expression: Fn.conditionEquals('Production', environmentParameter),
984
+ });
985
+
986
+ // Configuration value that is a different string based on IsProduction
987
+ const stage = Fn.conditionIf(isProd.logicalId, 'Beta', 'Prod').toString();
988
+
989
+ // Make Bucket creation condition to IsProduction by accessing
990
+ // and overriding the CloudFormation resource
991
+ const bucket = new s3.Bucket(this, 'Bucket');
992
+ const cfnBucket = myBucket.node.defaultChild as s3.CfnBucket;
993
+ cfnBucket.cfnOptions.condition = isProd;
994
+ ```
995
+
996
+ [cfn-intrinsics]: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html
997
+
998
+ ### Mappings
999
+
1000
+ CloudFormation [mappings][cfn-mappings] are created and queried using the
1001
+ `CfnMappings` class:
1002
+
1003
+ ```ts
1004
+ const regionTable = new CfnMapping(this, 'RegionTable', {
1005
+ mapping: {
1006
+ 'us-east-1': {
1007
+ regionName: 'US East (N. Virginia)',
1008
+ // ...
1009
+ },
1010
+ 'us-east-2': {
1011
+ regionName: 'US East (Ohio)',
1012
+ // ...
1013
+ },
1014
+ // ...
1015
+ }
1016
+ });
1017
+
1018
+ regionTable.findInMap(Aws.REGION, 'regionName')
1019
+ ```
1020
+
1021
+ This will yield the following template:
1022
+
1023
+ ```yaml
1024
+ Mappings:
1025
+ RegionTable:
1026
+ us-east-1:
1027
+ regionName: US East (N. Virginia)
1028
+ us-east-2:
1029
+ regionName: US East (Ohio)
1030
+ ```
1031
+
1032
+ Mappings can also be synthesized "lazily"; lazy mappings will only render a "Mappings"
1033
+ section in the synthesized CloudFormation template if some `findInMap` call is unable to
1034
+ immediately return a concrete value due to one or both of the keys being unresolved tokens
1035
+ (some value only available at deploy-time).
1036
+
1037
+ For example, the following code will not produce anything in the "Mappings" section. The
1038
+ call to `findInMap` will be able to resolve the value during synthesis and simply return
1039
+ `'US East (Ohio)'`.
1040
+
1041
+ ```ts
1042
+ const regionTable = new CfnMapping(this, 'RegionTable', {
1043
+ mapping: {
1044
+ 'us-east-1': {
1045
+ regionName: 'US East (N. Virginia)',
1046
+ },
1047
+ 'us-east-2': {
1048
+ regionName: 'US East (Ohio)',
1049
+ },
1050
+ },
1051
+ lazy: true,
1052
+ });
1053
+
1054
+ regionTable.findInMap('us-east-2', 'regionName');
1055
+ ```
1056
+
1057
+ On the other hand, the following code will produce the "Mappings" section shown above,
1058
+ since the top-level key is an unresolved token. The call to `findInMap` will return a token that resolves to
1059
+ `{ "Fn::FindInMap": [ "RegionTable", { "Ref": "AWS::Region" }, "regionName" ] }`.
1060
+
1061
+ ```ts
1062
+ declare const regionTable: CfnMapping;
1063
+
1064
+ regionTable.findInMap(Aws.REGION, 'regionName');
1065
+ ```
1066
+
1067
+ [cfn-mappings]: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html
1068
+
1069
+ ### Dynamic References
1070
+
1071
+ CloudFormation supports [dynamically resolving][cfn-dynamic-references] values
1072
+ for SSM parameters (including secure strings) and Secrets Manager. Encoding such
1073
+ references is done using the `CfnDynamicReference` class:
1074
+
1075
+ ```ts
1076
+ new CfnDynamicReference(
1077
+ CfnDynamicReferenceService.SECRETS_MANAGER,
1078
+ 'secret-id:secret-string:json-key:version-stage:version-id',
1079
+ );
1080
+ ```
1081
+
1082
+ [cfn-dynamic-references]: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html
1083
+
1084
+ ### Template Options & Transform
1085
+
1086
+ CloudFormation templates support a number of options, including which Macros or
1087
+ [Transforms][cfn-transform] to use when deploying the stack. Those can be
1088
+ configured using the `stack.templateOptions` property:
1089
+
1090
+ ```ts
1091
+ const stack = new Stack(app, 'StackName');
1092
+
1093
+ stack.templateOptions.description = 'This will appear in the AWS console';
1094
+ stack.templateOptions.transforms = ['AWS::Serverless-2016-10-31'];
1095
+ stack.templateOptions.metadata = {
1096
+ metadataKey: 'MetadataValue',
1097
+ };
1098
+ ```
1099
+
1100
+ [cfn-transform]: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-section-structure.html
1101
+
1102
+ ### Emitting Raw Resources
1103
+
1104
+ The `CfnResource` class allows emitting arbitrary entries in the
1105
+ [Resources][cfn-resources] section of the CloudFormation template.
1106
+
1107
+ ```ts
1108
+ new CfnResource(this, 'ResourceId', {
1109
+ type: 'AWS::S3::Bucket',
1110
+ properties: {
1111
+ BucketName: 'bucket-name'
1112
+ },
1113
+ });
1114
+ ```
1115
+
1116
+ As for any other resource, the logical ID in the CloudFormation template will be
1117
+ generated by the AWS CDK, but the type and properties will be copied verbatim in
1118
+ the synthesized template.
1119
+
1120
+ [cfn-resources]: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html
1121
+
1122
+ ### Including raw CloudFormation template fragments
1123
+
1124
+ When migrating a CloudFormation stack to the AWS CDK, it can be useful to
1125
+ include fragments of an existing template verbatim in the synthesized template.
1126
+ This can be achieved using the `CfnInclude` class.
1127
+
1128
+ ```ts
1129
+ new CfnInclude(this, 'ID', {
1130
+ template: {
1131
+ Resources: {
1132
+ Bucket: {
1133
+ Type: 'AWS::S3::Bucket',
1134
+ Properties: {
1135
+ BucketName: 'my-shiny-bucket'
1136
+ }
1137
+ }
1138
+ }
1139
+ },
1140
+ });
1141
+ ```
1142
+
1143
+ ### Termination Protection
1144
+
1145
+ You can prevent a stack from being accidentally deleted by enabling termination
1146
+ protection on the stack. If a user attempts to delete a stack with termination
1147
+ protection enabled, the deletion fails and the stack--including its status--remains
1148
+ unchanged. Enabling or disabling termination protection on a stack sets it for any
1149
+ nested stacks belonging to that stack as well. You can enable termination protection
1150
+ on a stack by setting the `terminationProtection` prop to `true`.
1151
+
1152
+ ```ts
1153
+ const stack = new Stack(app, 'StackName', {
1154
+ terminationProtection: true,
1155
+ });
1156
+ ```
1157
+
1158
+ By default, termination protection is disabled.
1159
+
1160
+ ### Description
1161
+
1162
+ You can add a description of the stack in the same way as `StackProps`.
1163
+
1164
+ ```ts
1165
+ const stack = new Stack(app, 'StackName', {
1166
+ description: 'This is a description.',
1167
+ });
1168
+ ```
1169
+
1170
+ ### CfnJson
1171
+
1172
+ `CfnJson` allows you to postpone the resolution of a JSON blob from
1173
+ deployment-time. This is useful in cases where the CloudFormation JSON template
1174
+ cannot express a certain value.
1175
+
1176
+ A common example is to use `CfnJson` in order to render a JSON map which needs
1177
+ to use intrinsic functions in keys. Since JSON map keys must be strings, it is
1178
+ impossible to use intrinsics in keys and `CfnJson` can help.
1179
+
1180
+ The following example defines an IAM role which can only be assumed by
1181
+ principals that are tagged with a specific tag.
1182
+
1183
+ ```ts
1184
+ const tagParam = new CfnParameter(this, 'TagName');
1185
+
1186
+ const stringEquals = new CfnJson(this, 'ConditionJson', {
1187
+ value: {
1188
+ [`aws:PrincipalTag/${tagParam.valueAsString}`]: true,
1189
+ },
1190
+ });
1191
+
1192
+ const principal = new iam.AccountRootPrincipal().withConditions({
1193
+ StringEquals: stringEquals,
1194
+ });
1195
+
1196
+ new iam.Role(this, 'MyRole', { assumedBy: principal });
1197
+ ```
1198
+
1199
+ **Explanation**: since in this example we pass the tag name through a parameter, it
1200
+ can only be resolved during deployment. The resolved value can be represented in
1201
+ the template through a `{ "Ref": "TagName" }`. However, since we want to use
1202
+ this value inside a [`aws:PrincipalTag/TAG-NAME`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principaltag)
1203
+ IAM operator, we need it in the *key* of a `StringEquals` condition. JSON keys
1204
+ *must be* strings, so to circumvent this limitation, we use `CfnJson`
1205
+ to "delay" the rendition of this template section to deploy-time. This means
1206
+ that the value of `StringEquals` in the template will be `{ "Fn::GetAtt": [ "ConditionJson", "Value" ] }`, and will only "expand" to the operator we synthesized during deployment.
1207
+
1208
+ ### Stack Resource Limit
1209
+
1210
+ When deploying to AWS CloudFormation, it needs to keep in check the amount of resources being added inside a Stack. Currently it's possible to check the limits in the [AWS CloudFormation quotas](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html) page.
1211
+
1212
+ It's possible to synthesize the project with more Resources than the allowed (or even reduce the number of Resources).
1213
+
1214
+ Set the context key `@aws-cdk/core:stackResourceLimit` with the proper value, being 0 for disable the limit of resources.
1215
+
1216
+ ## App Context
1217
+
1218
+ [Context values](https://docs.aws.amazon.com/cdk/v2/guide/context.html) are key-value pairs that can be associated with an app, stack, or construct.
1219
+ One common use case for context is to use it for enabling/disabling [feature flags](https://docs.aws.amazon.com/cdk/v2/guide/featureflags.html). There are several places
1220
+ where context can be specified. They are listed below in the order they are evaluated (items at the
1221
+ top take precedence over those below).
1222
+
1223
+ - The `node.setContext()` method
1224
+ - The `postCliContext` prop when you create an `App`
1225
+ - The CLI via the `--context` CLI argument
1226
+ - The `cdk.json` file via the `context` key:
1227
+ - The `cdk.context.json` file:
1228
+ - The `~/.cdk.json` file via the `context` key:
1229
+ - The `context` prop when you create an `App`
1230
+
1231
+ ### Examples of setting context
1232
+
1233
+ ```ts
1234
+ new App({
1235
+ context: {
1236
+ '@aws-cdk/core:newStyleStackSynthesis': true,
1237
+ },
1238
+ });
1239
+ ```
1240
+
1241
+ ```ts
1242
+ const app = new App();
1243
+ app.node.setContext('@aws-cdk/core:newStyleStackSynthesis', true);
1244
+ ```
1245
+
1246
+ ```ts
1247
+ new App({
1248
+ postCliContext: {
1249
+ '@aws-cdk/core:newStyleStackSynthesis': true,
1250
+ },
1251
+ });
1252
+ ```
1253
+
1254
+ ```console
1255
+ cdk synth --context @aws-cdk/core:newStyleStackSynthesis=true
1256
+ ```
1257
+
1258
+ _cdk.json_
1259
+
1260
+ ```json
1261
+ {
1262
+ "context": {
1263
+ "@aws-cdk/core:newStyleStackSynthesis": true
1264
+ }
1265
+ }
1266
+ ```
1267
+
1268
+ _cdk.context.json_
1269
+
1270
+ ```json
1271
+ {
1272
+ "@aws-cdk/core:newStyleStackSynthesis": true
1273
+ }
1274
+ ```
1275
+
1276
+ _~/.cdk.json_
1277
+
1278
+ ```json
1279
+ {
1280
+ "context": {
1281
+ "@aws-cdk/core:newStyleStackSynthesis": true
1282
+ }
1283
+ }
1284
+ ```
1285
+
1286
+ ## IAM Permissions Boundary
1287
+
1288
+ It is possible to apply an [IAM permissions boundary](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html)
1289
+ to all roles within a specific construct scope. The most common use case would
1290
+ be to apply a permissions boundary at the `Stage` level.
1291
+
1292
+ ```ts
1293
+ declare const app: App;
1294
+
1295
+ const prodStage = new Stage(app, 'ProdStage', {
1296
+ permissionsBoundary: PermissionsBoundary.fromName('cdk-${Qualifier}-PermissionsBoundary'),
1297
+ });
1298
+ ```
1299
+
1300
+ Any IAM Roles or Users created within this Stage will have the default
1301
+ permissions boundary attached.
1302
+
1303
+ For more details see the [Permissions Boundary](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam-readme.html#permissions-boundaries) section in the IAM guide.
1304
+
1305
+ <!--END CORE DOCUMENTATION-->