# Include CloudFormation templates in the CDK
<!--BEGIN STABILITY BANNER-->---
![End-of-Support](https://img.shields.io/badge/End--of--Support-critical.svg?style=for-the-badge)
> AWS CDK v1 has reached End-of-Support on 2023-06-01.
> This package is no longer being updated, and users should migrate to AWS CDK v2.
>
> For more information on how to migrate, see the [*Migrating to AWS CDK v2* guide](https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html).
---
<!--END STABILITY BANNER-->
This module contains a set of classes whose goal is to facilitate working
with existing CloudFormation templates in the CDK.
It can be thought of as an extension of the capabilities of the
[`CfnInclude` class](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html).
## Basic usage
Assume we have a file with an existing template.
It could be in JSON format, in a file `my-template.json`:
```json
{
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "some-bucket-name"
}
}
}
}
```
Or it could by in YAML format, in a file `my-template.yaml`:
```yaml
Resources:
Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: some-bucket-name
```
It can be included in a CDK application with the following code:
```python
cfn_template = cfn_inc.CfnInclude(self, "Template",
template_file="my-template.json"
)
```
Or, if your template uses YAML:
```python
cfn_template = cfn_inc.CfnInclude(self, "Template",
template_file="my-template.yaml"
)
```
**Note**: different YAML parsers sometimes don't agree on what exactly constitutes valid YAML.
If you get a YAML exception when including your template,
try converting it to JSON, and including that file instead.
If you're downloading your template from the CloudFormation AWS Console,
you can easily get it in JSON format by clicking the 'View in Designer'
button on the 'Template' tab -
once in Designer, select JSON in the "Choose template language"
radio buttons on the bottom pane.
This will add all resources from `my-template.json` / `my-template.yaml` into the CDK application,
preserving their original logical IDs from the template file.
Note that this including process will *not* execute any
[CloudFormation transforms](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-macros.html) -
including the [Serverless transform](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-aws-serverless.html).
Any resource from the included template can be retrieved by referring to it by its logical ID from the template.
If you know the class of the CDK object that corresponds to that resource,
you can cast the returned object to the correct type:
```python
# cfn_template: cfn_inc.CfnInclude
cfn_bucket = cfn_template.get_resource("Bucket")
```
Note that any resources not present in the latest version of the CloudFormation schema
at the time of publishing the version of this module that you depend on,
including [Custom Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html),
will be returned as instances of the class `CfnResource`,
and so cannot be cast to a different resource type.
Any modifications made to that resource will be reflected in the resulting CDK template;
for example, the name of the bucket can be changed:
```python
# cfn_template: cfn_inc.CfnInclude
cfn_bucket = cfn_template.get_resource("Bucket")
cfn_bucket.bucket_name = "my-bucket-name"
```
You can also refer to the resource when defining other constructs,
including the higher-level ones
(those whose name does not start with `Cfn`),
for example:
```python
# cfn_template: cfn_inc.CfnInclude
cfn_bucket = cfn_template.get_resource("Bucket")
role = iam.Role(self, "Role",
assumed_by=iam.AnyPrincipal()
)
role.add_to_policy(iam.PolicyStatement(
actions=["s3:*"],
resources=[cfn_bucket.attr_arn]
))
```
### Converting L1 resources to L2
The resources the `getResource` method returns are what the CDK calls
[Layer 1 resources](https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html#cfn_layer_cfn)
(like `CfnBucket`).
However, in many places in the Construct Library,
the CDK requires so-called Layer 2 resources, like `IBucket`.
There are two ways of going from an L1 to an L2 resource.
#### Using`fromCfn*()` methods
This is the preferred method of converting an L1 resource to an L2.
It works by invoking a static method of the class of the L2 resource
whose name starts with `fromCfn` -
for example, for KMS Keys, that would be the `Kms.fromCfnKey()` method -
and passing the L1 instance as an argument:
```python
# cfn_template: cfn_inc.CfnInclude
cfn_key = cfn_template.get_resource("Key")
key = kms.Key.from_cfn_key(cfn_key)
```
This returns an instance of the `kms.IKey` type that can be passed anywhere in the CDK an `IKey` is expected.
What is more, that `IKey` instance will be mutable -
which means calling any mutating methods on it,
like `addToResourcePolicy()`,
will be reflected in the resulting template.
Note that, in some cases, the `fromCfn*()` method might not be able to create an L2 from the underlying L1.
This can happen when the underlying L1 heavily uses CloudFormation functions.
For example, if you tried to create an L2 `IKey`
from an L1 represented as this CloudFormation template:
```json
{
"Resources": {
"Key": {
"Type": "AWS::KMS::Key",
"Properties": {
"KeyPolicy": {
"Statement": [
{
"Fn::If": [
"Condition",
{
"Action": "kms:if-action",
"Resource": "*",
"Principal": "*",
"Effect": "Allow"
},
{
"Action": "kms:else-action",
"Resource": "*",
"Principal": "*",
"Effect": "Allow"
}
]
}
],
"Version": "2012-10-17"
}
}
}
}
}
```
The `Key.fromCfnKey()` method does not know how to translate that into CDK L2 concepts,
and would throw an exception.
In those cases, you need the use the second method of converting an L1 to an L2.
#### Using `from*Name/Arn/Attributes()` methods
If the resource you need does not have a `fromCfn*()` method,
or if it does, but it throws an exception for your particular L1,
you need to use the second method of converting an L1 resource to L2.
Each L2 class has static factory methods with names like `from*Name()`,
`from*Arn()`, and/or `from*Attributes()`.
You can obtain an L2 resource from an L1 by passing the correct properties of the L1 as the arguments to those methods:
```python
# cfn_template: cfn_inc.CfnInclude
# using from*Attributes()
# private_cfn_subnet1: ec2.CfnSubnet
# private_cfn_subnet2: ec2.CfnSubnet
# using from*Name()
cfn_bucket = cfn_template.get_resource("Bucket")
bucket = s3.Bucket.from_bucket_name(self, "L2Bucket", cfn_bucket.ref)
# using from*Arn()
cfn_key = cfn_template.get_resource("Key")
key = kms.Key.from_key_arn(self, "L2Key", cfn_key.attr_arn)
cfn_vpc = cfn_template.get_resource("Vpc")
vpc = ec2.Vpc.from_vpc_attributes(self, "L2Vpc",
vpc_id=cfn_vpc.ref,
availability_zones=core.Fn.get_azs(),
private_subnet_ids=[private_cfn_subnet1.ref, private_cfn_subnet2.ref]
)
```
As long as they just need to be referenced,
and not changed in any way, everything should work;
however, note that resources returned from those methods,
unlike those returned by `fromCfn*()` methods,
are immutable, which means calling any mutating methods on them will have no effect.
You will have to mutate the underlying L1 in order to change them.
## Non-resource template elements
In addition to resources,
you can also retrieve and mutate all other template elements:
* [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html):
```python
# cfn_template: cfn_inc.CfnInclude
param = cfn_template.get_parameter("MyParameter")
# mutating the parameter
param.default = "MyDefault"
```
* [Conditions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html):
```python
# cfn_template: cfn_inc.CfnInclude
condition = cfn_template.get_condition("MyCondition")
# mutating the condition
condition.expression = core.Fn.condition_equals(1, 2)
```
* [Mappings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html):
```python
# cfn_template: cfn_inc.CfnInclude
mapping = cfn_template.get_mapping("MyMapping")
# mutating the mapping
mapping.set_value("my-region", "AMI", "ami-04681a1dbd79675a5")
```
* [Service Catalog template Rules](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/reference-template_constraint_rules.html):
```python
# cfn_template: cfn_inc.CfnInclude
# mutating the rule
# my_parameter: core.CfnParameter
rule = cfn_template.get_rule("MyRule")
rule.add_assertion(core.Fn.condition_contains(["m1.small"], my_parameter.value_as_string), "MyParameter has to be m1.small")
```
* [Outputs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html):
```python
# cfn_template: cfn_inc.CfnInclude
# mutating the output
# cfn_bucket: s3.CfnBucket
output = cfn_template.get_output("MyOutput")
output.value = cfn_bucket.attr_arn
```
* [Hooks for blue-green deployments](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/blue-green.html):
```python
# cfn_template: cfn_inc.CfnInclude
# mutating the hook
# my_role: iam.Role
hook = cfn_template.get_hook("MyOutput")
code_deploy_hook = hook
code_deploy_hook.service_role = my_role.role_arn
```
## Parameter replacement
If your existing template uses CloudFormation Parameters,
you may want to remove them in favor of build-time values.
You can do that using the `parameters` property:
```python
cfn_inc.CfnInclude(self, "includeTemplate",
template_file="path/to/my/template",
parameters={
"MyParam": "my-value"
}
)
```
This will replace all references to `MyParam` with the string `'my-value'`,
and `MyParam` will be removed from the 'Parameters' section of the resulting template.
## Nested Stacks
This module also supports templates that use [nested stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html).
For example, if you have the following parent template:
```json
{
"Resources": {
"ChildStack": {
"Type": "AWS::CloudFormation::Stack",
"Properties": {
"TemplateURL": "https://my-s3-template-source.s3.amazonaws.com/child-stack.json"
}
}
}
}
```
where the child template pointed to by `https://my-s3-template-source.s3.amazonaws.com/child-stack.json` is:
```json
{
"Resources": {
"MyBucket": {
"Type": "AWS::S3::Bucket"
}
}
}
```
You can include both the parent stack,
and the nested stack in your CDK application as follows:
```python
parent_template = cfn_inc.CfnInclude(self, "ParentStack",
template_file="path/to/my-parent-template.json",
load_nested_stacks={
"ChildStack": cfn_inc.CfnIncludeProps(
template_file="path/to/my-nested-template.json"
)
}
)
```
Here, `path/to/my-nested-template.json`
represents the path on disk to the downloaded template file from the original template URL of the nested stack
(`https://my-s3-template-source.s3.amazonaws.com/child-stack.json`).
In the CDK application,
this file will be turned into an [Asset](https://docs.aws.amazon.com/cdk/latest/guide/assets.html),
and the `TemplateURL` property of the nested stack resource
will be modified to point to that asset.
The included nested stack can be accessed with the `getNestedStack` method:
```python
# parent_template: cfn_inc.CfnInclude
included_child_stack = parent_template.get_nested_stack("ChildStack")
child_stack = included_child_stack.stack
child_template = included_child_stack.included_template
```
Now you can reference resources from `ChildStack`,
and modify them like any other included template:
```python
# child_template: cfn_inc.CfnInclude
cfn_bucket = child_template.get_resource("MyBucket")
cfn_bucket.bucket_name = "my-new-bucket-name"
role = iam.Role(self, "MyRole",
assumed_by=iam.AccountRootPrincipal()
)
role.add_to_policy(iam.PolicyStatement(
actions=["s3:GetObject*", "s3:GetBucket*", "s3:List*"
],
resources=[cfn_bucket.attr_arn]
))
```
You can also include the nested stack after the `CfnInclude` object was created,
instead of doing it on construction:
```python
# parent_template: cfn_inc.CfnInclude
included_child_stack = parent_template.load_nested_stack("ChildTemplate",
template_file="path/to/my-nested-template.json"
)
```
## Vending CloudFormation templates as Constructs
In many cases, there are existing CloudFormation templates that are not entire applications,
but more like specialized fragments, implementing a particular pattern or best practice.
If you have templates like that,
you can use the `CfnInclude` class to vend them as CDK Constructs:
```python
from constructs import Construct
import aws_cdk.cloudformation_include as cfn_inc
import path as path
class MyConstruct(Construct):
def __init__(self, scope, id):
super().__init__(scope, id)
# include a template inside the Construct
cfn_inc.CfnInclude(self, "MyConstruct",
template_file=path.join(__dirname, "my-template.json"),
preserve_logical_ids=False
)
```
Notice the `preserveLogicalIds` parameter -
it makes sure the logical IDs of all the included template elements are re-named using CDK's algorithm,
guaranteeing they are unique within your application.
Without that parameter passed,
instantiating `MyConstruct` twice in the same Stack would result in duplicated logical IDs.
Raw data
{
"_id": null,
"home_page": "https://github.com/aws/aws-cdk",
"name": "aws-cdk.cloudformation-include",
"maintainer": "",
"docs_url": null,
"requires_python": "~=3.7",
"maintainer_email": "",
"keywords": "",
"author": "Amazon Web Services",
"author_email": "",
"download_url": "https://files.pythonhosted.org/packages/50/91/0c5593afba9510cfab681ffbdef8bd855d678661dddfbe1fc022f22823e7/aws-cdk.cloudformation-include-1.204.0.tar.gz",
"platform": null,
"description": "# Include CloudFormation templates in the CDK\n\n<!--BEGIN STABILITY BANNER-->---\n\n\n![End-of-Support](https://img.shields.io/badge/End--of--Support-critical.svg?style=for-the-badge)\n\n> AWS CDK v1 has reached End-of-Support on 2023-06-01.\n> This package is no longer being updated, and users should migrate to AWS CDK v2.\n>\n> For more information on how to migrate, see the [*Migrating to AWS CDK v2* guide](https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html).\n\n---\n<!--END STABILITY BANNER-->\n\nThis module contains a set of classes whose goal is to facilitate working\nwith existing CloudFormation templates in the CDK.\nIt can be thought of as an extension of the capabilities of the\n[`CfnInclude` class](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html).\n\n## Basic usage\n\nAssume we have a file with an existing template.\nIt could be in JSON format, in a file `my-template.json`:\n\n```json\n{\n \"Resources\": {\n \"Bucket\": {\n \"Type\": \"AWS::S3::Bucket\",\n \"Properties\": {\n \"BucketName\": \"some-bucket-name\"\n }\n }\n }\n}\n```\n\nOr it could by in YAML format, in a file `my-template.yaml`:\n\n```yaml\nResources:\n Bucket:\n Type: AWS::S3::Bucket\n Properties:\n BucketName: some-bucket-name\n```\n\nIt can be included in a CDK application with the following code:\n\n```python\ncfn_template = cfn_inc.CfnInclude(self, \"Template\",\n template_file=\"my-template.json\"\n)\n```\n\nOr, if your template uses YAML:\n\n```python\ncfn_template = cfn_inc.CfnInclude(self, \"Template\",\n template_file=\"my-template.yaml\"\n)\n```\n\n**Note**: different YAML parsers sometimes don't agree on what exactly constitutes valid YAML.\nIf you get a YAML exception when including your template,\ntry converting it to JSON, and including that file instead.\nIf you're downloading your template from the CloudFormation AWS Console,\nyou can easily get it in JSON format by clicking the 'View in Designer'\nbutton on the 'Template' tab -\nonce in Designer, select JSON in the \"Choose template language\"\nradio buttons on the bottom pane.\n\nThis will add all resources from `my-template.json` / `my-template.yaml` into the CDK application,\npreserving their original logical IDs from the template file.\n\nNote that this including process will *not* execute any\n[CloudFormation transforms](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-macros.html) -\nincluding the [Serverless transform](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-aws-serverless.html).\n\nAny resource from the included template can be retrieved by referring to it by its logical ID from the template.\nIf you know the class of the CDK object that corresponds to that resource,\nyou can cast the returned object to the correct type:\n\n```python\n# cfn_template: cfn_inc.CfnInclude\n\ncfn_bucket = cfn_template.get_resource(\"Bucket\")\n```\n\nNote that any resources not present in the latest version of the CloudFormation schema\nat the time of publishing the version of this module that you depend on,\nincluding [Custom Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html),\nwill be returned as instances of the class `CfnResource`,\nand so cannot be cast to a different resource type.\n\nAny modifications made to that resource will be reflected in the resulting CDK template;\nfor example, the name of the bucket can be changed:\n\n```python\n# cfn_template: cfn_inc.CfnInclude\n\ncfn_bucket = cfn_template.get_resource(\"Bucket\")\ncfn_bucket.bucket_name = \"my-bucket-name\"\n```\n\nYou can also refer to the resource when defining other constructs,\nincluding the higher-level ones\n(those whose name does not start with `Cfn`),\nfor example:\n\n```python\n# cfn_template: cfn_inc.CfnInclude\n\ncfn_bucket = cfn_template.get_resource(\"Bucket\")\n\nrole = iam.Role(self, \"Role\",\n assumed_by=iam.AnyPrincipal()\n)\nrole.add_to_policy(iam.PolicyStatement(\n actions=[\"s3:*\"],\n resources=[cfn_bucket.attr_arn]\n))\n```\n\n### Converting L1 resources to L2\n\nThe resources the `getResource` method returns are what the CDK calls\n[Layer 1 resources](https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html#cfn_layer_cfn)\n(like `CfnBucket`).\nHowever, in many places in the Construct Library,\nthe CDK requires so-called Layer 2 resources, like `IBucket`.\nThere are two ways of going from an L1 to an L2 resource.\n\n#### Using`fromCfn*()` methods\n\nThis is the preferred method of converting an L1 resource to an L2.\nIt works by invoking a static method of the class of the L2 resource\nwhose name starts with `fromCfn` -\nfor example, for KMS Keys, that would be the `Kms.fromCfnKey()` method -\nand passing the L1 instance as an argument:\n\n```python\n# cfn_template: cfn_inc.CfnInclude\n\ncfn_key = cfn_template.get_resource(\"Key\")\nkey = kms.Key.from_cfn_key(cfn_key)\n```\n\nThis returns an instance of the `kms.IKey` type that can be passed anywhere in the CDK an `IKey` is expected.\nWhat is more, that `IKey` instance will be mutable -\nwhich means calling any mutating methods on it,\nlike `addToResourcePolicy()`,\nwill be reflected in the resulting template.\n\nNote that, in some cases, the `fromCfn*()` method might not be able to create an L2 from the underlying L1.\nThis can happen when the underlying L1 heavily uses CloudFormation functions.\nFor example, if you tried to create an L2 `IKey`\nfrom an L1 represented as this CloudFormation template:\n\n```json\n{\n \"Resources\": {\n \"Key\": {\n \"Type\": \"AWS::KMS::Key\",\n \"Properties\": {\n \"KeyPolicy\": {\n \"Statement\": [\n {\n \"Fn::If\": [\n \"Condition\",\n {\n \"Action\": \"kms:if-action\",\n \"Resource\": \"*\",\n \"Principal\": \"*\",\n \"Effect\": \"Allow\"\n },\n {\n \"Action\": \"kms:else-action\",\n \"Resource\": \"*\",\n \"Principal\": \"*\",\n \"Effect\": \"Allow\"\n }\n ]\n }\n ],\n \"Version\": \"2012-10-17\"\n }\n }\n }\n }\n}\n```\n\nThe `Key.fromCfnKey()` method does not know how to translate that into CDK L2 concepts,\nand would throw an exception.\n\nIn those cases, you need the use the second method of converting an L1 to an L2.\n\n#### Using `from*Name/Arn/Attributes()` methods\n\nIf the resource you need does not have a `fromCfn*()` method,\nor if it does, but it throws an exception for your particular L1,\nyou need to use the second method of converting an L1 resource to L2.\n\nEach L2 class has static factory methods with names like `from*Name()`,\n`from*Arn()`, and/or `from*Attributes()`.\nYou can obtain an L2 resource from an L1 by passing the correct properties of the L1 as the arguments to those methods:\n\n```python\n# cfn_template: cfn_inc.CfnInclude\n\n# using from*Attributes()\n# private_cfn_subnet1: ec2.CfnSubnet\n# private_cfn_subnet2: ec2.CfnSubnet\n\n\n# using from*Name()\ncfn_bucket = cfn_template.get_resource(\"Bucket\")\nbucket = s3.Bucket.from_bucket_name(self, \"L2Bucket\", cfn_bucket.ref)\n\n# using from*Arn()\ncfn_key = cfn_template.get_resource(\"Key\")\nkey = kms.Key.from_key_arn(self, \"L2Key\", cfn_key.attr_arn)\ncfn_vpc = cfn_template.get_resource(\"Vpc\")\nvpc = ec2.Vpc.from_vpc_attributes(self, \"L2Vpc\",\n vpc_id=cfn_vpc.ref,\n availability_zones=core.Fn.get_azs(),\n private_subnet_ids=[private_cfn_subnet1.ref, private_cfn_subnet2.ref]\n)\n```\n\nAs long as they just need to be referenced,\nand not changed in any way, everything should work;\nhowever, note that resources returned from those methods,\nunlike those returned by `fromCfn*()` methods,\nare immutable, which means calling any mutating methods on them will have no effect.\nYou will have to mutate the underlying L1 in order to change them.\n\n## Non-resource template elements\n\nIn addition to resources,\nyou can also retrieve and mutate all other template elements:\n\n* [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html):\n\n ```python\n # cfn_template: cfn_inc.CfnInclude\n\n param = cfn_template.get_parameter(\"MyParameter\")\n\n # mutating the parameter\n param.default = \"MyDefault\"\n ```\n* [Conditions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html):\n\n ```python\n # cfn_template: cfn_inc.CfnInclude\n\n condition = cfn_template.get_condition(\"MyCondition\")\n\n # mutating the condition\n condition.expression = core.Fn.condition_equals(1, 2)\n ```\n* [Mappings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html):\n\n ```python\n # cfn_template: cfn_inc.CfnInclude\n\n mapping = cfn_template.get_mapping(\"MyMapping\")\n\n # mutating the mapping\n mapping.set_value(\"my-region\", \"AMI\", \"ami-04681a1dbd79675a5\")\n ```\n* [Service Catalog template Rules](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/reference-template_constraint_rules.html):\n\n ```python\n # cfn_template: cfn_inc.CfnInclude\n\n # mutating the rule\n # my_parameter: core.CfnParameter\n\n rule = cfn_template.get_rule(\"MyRule\")\n rule.add_assertion(core.Fn.condition_contains([\"m1.small\"], my_parameter.value_as_string), \"MyParameter has to be m1.small\")\n ```\n* [Outputs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html):\n\n ```python\n # cfn_template: cfn_inc.CfnInclude\n\n # mutating the output\n # cfn_bucket: s3.CfnBucket\n\n output = cfn_template.get_output(\"MyOutput\")\n output.value = cfn_bucket.attr_arn\n ```\n* [Hooks for blue-green deployments](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/blue-green.html):\n\n ```python\n # cfn_template: cfn_inc.CfnInclude\n\n # mutating the hook\n # my_role: iam.Role\n\n hook = cfn_template.get_hook(\"MyOutput\")\n code_deploy_hook = hook\n code_deploy_hook.service_role = my_role.role_arn\n ```\n\n## Parameter replacement\n\nIf your existing template uses CloudFormation Parameters,\nyou may want to remove them in favor of build-time values.\nYou can do that using the `parameters` property:\n\n```python\ncfn_inc.CfnInclude(self, \"includeTemplate\",\n template_file=\"path/to/my/template\",\n parameters={\n \"MyParam\": \"my-value\"\n }\n)\n```\n\nThis will replace all references to `MyParam` with the string `'my-value'`,\nand `MyParam` will be removed from the 'Parameters' section of the resulting template.\n\n## Nested Stacks\n\nThis module also supports templates that use [nested stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html).\n\nFor example, if you have the following parent template:\n\n```json\n{\n \"Resources\": {\n \"ChildStack\": {\n \"Type\": \"AWS::CloudFormation::Stack\",\n \"Properties\": {\n \"TemplateURL\": \"https://my-s3-template-source.s3.amazonaws.com/child-stack.json\"\n }\n }\n }\n}\n```\n\nwhere the child template pointed to by `https://my-s3-template-source.s3.amazonaws.com/child-stack.json` is:\n\n```json\n{\n \"Resources\": {\n \"MyBucket\": {\n \"Type\": \"AWS::S3::Bucket\"\n }\n }\n}\n```\n\nYou can include both the parent stack,\nand the nested stack in your CDK application as follows:\n\n```python\nparent_template = cfn_inc.CfnInclude(self, \"ParentStack\",\n template_file=\"path/to/my-parent-template.json\",\n load_nested_stacks={\n \"ChildStack\": cfn_inc.CfnIncludeProps(\n template_file=\"path/to/my-nested-template.json\"\n )\n }\n)\n```\n\nHere, `path/to/my-nested-template.json`\nrepresents the path on disk to the downloaded template file from the original template URL of the nested stack\n(`https://my-s3-template-source.s3.amazonaws.com/child-stack.json`).\nIn the CDK application,\nthis file will be turned into an [Asset](https://docs.aws.amazon.com/cdk/latest/guide/assets.html),\nand the `TemplateURL` property of the nested stack resource\nwill be modified to point to that asset.\n\nThe included nested stack can be accessed with the `getNestedStack` method:\n\n```python\n# parent_template: cfn_inc.CfnInclude\n\n\nincluded_child_stack = parent_template.get_nested_stack(\"ChildStack\")\nchild_stack = included_child_stack.stack\nchild_template = included_child_stack.included_template\n```\n\nNow you can reference resources from `ChildStack`,\nand modify them like any other included template:\n\n```python\n# child_template: cfn_inc.CfnInclude\n\n\ncfn_bucket = child_template.get_resource(\"MyBucket\")\ncfn_bucket.bucket_name = \"my-new-bucket-name\"\n\nrole = iam.Role(self, \"MyRole\",\n assumed_by=iam.AccountRootPrincipal()\n)\n\nrole.add_to_policy(iam.PolicyStatement(\n actions=[\"s3:GetObject*\", \"s3:GetBucket*\", \"s3:List*\"\n ],\n resources=[cfn_bucket.attr_arn]\n))\n```\n\nYou can also include the nested stack after the `CfnInclude` object was created,\ninstead of doing it on construction:\n\n```python\n# parent_template: cfn_inc.CfnInclude\n\nincluded_child_stack = parent_template.load_nested_stack(\"ChildTemplate\",\n template_file=\"path/to/my-nested-template.json\"\n)\n```\n\n## Vending CloudFormation templates as Constructs\n\nIn many cases, there are existing CloudFormation templates that are not entire applications,\nbut more like specialized fragments, implementing a particular pattern or best practice.\nIf you have templates like that,\nyou can use the `CfnInclude` class to vend them as CDK Constructs:\n\n```python\nfrom constructs import Construct\nimport aws_cdk.cloudformation_include as cfn_inc\nimport path as path\n\nclass MyConstruct(Construct):\n def __init__(self, scope, id):\n super().__init__(scope, id)\n\n # include a template inside the Construct\n cfn_inc.CfnInclude(self, \"MyConstruct\",\n template_file=path.join(__dirname, \"my-template.json\"),\n preserve_logical_ids=False\n )\n```\n\nNotice the `preserveLogicalIds` parameter -\nit makes sure the logical IDs of all the included template elements are re-named using CDK's algorithm,\nguaranteeing they are unique within your application.\nWithout that parameter passed,\ninstantiating `MyConstruct` twice in the same Stack would result in duplicated logical IDs.\n",
"bugtrack_url": null,
"license": "Apache-2.0",
"summary": "A package that facilitates working with existing CloudFormation templates in the CDK",
"version": "1.204.0",
"project_urls": {
"Homepage": "https://github.com/aws/aws-cdk",
"Source": "https://github.com/aws/aws-cdk.git"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "a15461a9968f6c2e5ff1d1209eeff517ca29d428aa7d893a8b440e1633ca9484",
"md5": "a3f65c0e930a83ed58c8506fa8d2c221",
"sha256": "1db41cf39ea2dbbeaaf8bab487e653a3bca373073996cbc3d111dffd8f095c8c"
},
"downloads": -1,
"filename": "aws_cdk.cloudformation_include-1.204.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "a3f65c0e930a83ed58c8506fa8d2c221",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "~=3.7",
"size": 199333,
"upload_time": "2023-06-19T21:02:07",
"upload_time_iso_8601": "2023-06-19T21:02:07.692183Z",
"url": "https://files.pythonhosted.org/packages/a1/54/61a9968f6c2e5ff1d1209eeff517ca29d428aa7d893a8b440e1633ca9484/aws_cdk.cloudformation_include-1.204.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "50910c5593afba9510cfab681ffbdef8bd855d678661dddfbe1fc022f22823e7",
"md5": "d6273a79526a8915023610074cfe3583",
"sha256": "3850751bb1c696929b71681e10a55bd3f972786832df0c753401d36b122bce56"
},
"downloads": -1,
"filename": "aws-cdk.cloudformation-include-1.204.0.tar.gz",
"has_sig": false,
"md5_digest": "d6273a79526a8915023610074cfe3583",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "~=3.7",
"size": 202520,
"upload_time": "2023-06-19T21:08:10",
"upload_time_iso_8601": "2023-06-19T21:08:10.979209Z",
"url": "https://files.pythonhosted.org/packages/50/91/0c5593afba9510cfab681ffbdef8bd855d678661dddfbe1fc022f22823e7/aws-cdk.cloudformation-include-1.204.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2023-06-19 21:08:10",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "aws",
"github_project": "aws-cdk",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "aws-cdk.cloudformation-include"
}