Skip to content
v2.274.0

Include CloudFormation templates in the CDK ​

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.

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": "amzn-s3-demo-bucket"
      }
    }
  }
}

Or it could by in YAML format, in a file my-template.yaml:

yaml
Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: amzn-s3-demo-bucket

It can be included in a CDK application with the following code:

ts
const cfnTemplate = new cfn_inc.CfnInclude(this, 'Template', {
  templateFile: 'my-template.json',
});
python
cfn_template = cfn_inc.CfnInclude(self, "Template",
    template_file="my-template.json"
)
java
CfnInclude cfnTemplate = CfnInclude.Builder.create(this, "Template")
        .templateFile("my-template.json")
        .build();
csharp
var cfnTemplate = new CfnInclude(this, "Template", new CfnIncludeProps {
    TemplateFile = "my-template.json"
});
go
cfnTemplate := cfn_inc.NewCfnInclude(this, jsii.String("Template"), &CfnIncludeProps{
	TemplateFile: jsii.String("my-template.json"),
})

Or, if your template uses YAML:

ts
const cfnTemplate = new cfn_inc.CfnInclude(this, 'Template', {
  templateFile: 'my-template.yaml',
});
python
cfn_template = cfn_inc.CfnInclude(self, "Template",
    template_file="my-template.yaml"
)
java
CfnInclude cfnTemplate = CfnInclude.Builder.create(this, "Template")
        .templateFile("my-template.yaml")
        .build();
csharp
var cfnTemplate = new CfnInclude(this, "Template", new CfnIncludeProps {
    TemplateFile = "my-template.yaml"
});
go
cfnTemplate := cfn_inc.NewCfnInclude(this, jsii.String("Template"), &CfnIncludeProps{
	TemplateFile: jsii.String("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.

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:

ts
declare const cfnTemplate: cfn_inc.CfnInclude;
const cfnBucket = cfnTemplate.getResource('Bucket') as s3.CfnBucket;
// cfnBucket is of type s3.CfnBucket
python
# cfn_template: cfn_inc.CfnInclude

cfn_bucket = cfn_template.get_resource("Bucket")
java
CfnInclude cfnTemplate;

CfnBucket cfnBucket = (CfnBucket)cfnTemplate.getResource("Bucket");
csharp
CfnInclude cfnTemplate;

var cfnBucket = (CfnBucket)cfnTemplate.GetResource("Bucket");
go
var cfnTemplate CfnInclude

cfnBucket := cfnTemplate.GetResource(jsii.String("Bucket")).(CfnBucket)

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, 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:

ts
declare const cfnTemplate: cfn_inc.CfnInclude;
const cfnBucket = cfnTemplate.getResource('Bucket') as s3.CfnBucket;
cfnBucket.bucketName = 'amzn-s3-demo-bucket';
python
# cfn_template: cfn_inc.CfnInclude

cfn_bucket = cfn_template.get_resource("Bucket")
cfn_bucket.bucket_name = "amzn-s3-demo-bucket"
java
CfnInclude cfnTemplate;

CfnBucket cfnBucket = (CfnBucket)cfnTemplate.getResource("Bucket");
cfnBucket.getBucketName() = "amzn-s3-demo-bucket";
csharp
CfnInclude cfnTemplate;

var cfnBucket = (CfnBucket)cfnTemplate.GetResource("Bucket");
cfnBucket.BucketName = "amzn-s3-demo-bucket";
go
var cfnTemplate CfnInclude

cfnBucket := cfnTemplate.GetResource(jsii.String("Bucket")).(CfnBucket)
cfnBucket.bucketName = "amzn-s3-demo-bucket"

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:

ts
declare const cfnTemplate: cfn_inc.CfnInclude;
const cfnBucket = cfnTemplate.getResource('Bucket') as s3.CfnBucket;

const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.AnyPrincipal(),
});
role.addToPolicy(new iam.PolicyStatement({
  actions: ['s3:*'],
  resources: [cfnBucket.attrArn],
}));
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]
))
java
CfnInclude cfnTemplate;

CfnBucket cfnBucket = (CfnBucket)cfnTemplate.getResource("Bucket");

Role role = Role.Builder.create(this, "Role")
        .assumedBy(new AnyPrincipal())
        .build();
role.addToPolicy(PolicyStatement.Builder.create()
        .actions(List.of("s3:*"))
        .resources(List.of(cfnBucket.getAttrArn()))
        .build());
csharp
CfnInclude cfnTemplate;

var cfnBucket = (CfnBucket)cfnTemplate.GetResource("Bucket");

var role = new Role(this, "Role", new RoleProps {
    AssumedBy = new AnyPrincipal()
});
role.AddToPolicy(new PolicyStatement(new PolicyStatementProps {
    Actions = new [] { "s3:*" },
    Resources = new [] { cfnBucket.AttrArn }
}));
go
var cfnTemplate CfnInclude

cfnBucket := cfnTemplate.GetResource(jsii.String("Bucket")).(CfnBucket)

role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewAnyPrincipal(),
})
role.AddToPolicy(iam.NewPolicyStatement(&PolicyStatementProps{
	Actions: []*string{
		jsii.String("s3:*"),
	},
	Resources: []*string{
		cfnBucket.attrArn,
	},
}))

Migrating templates that use Transforms ​

You can use this module to migrate templates that use CloudFormation transforms - including the Serverless transform.

The CDK including process does not execute Transforms, and the cdk diff command by default compares against the original (meaning, unprocessed) template. So, if you're downloading the template to include from the CloudFormation AWS Console, make sure to download the unprocessed template (the "View processed template" checkbox is left unchecked, which is the default):

unprocessed template in the CloudFormation AWS Console

However, certain unprocessed templates can fail when used with the CfnInclude class. The most common reason for the failure is that the unprocessed template can contain cycles between resources, which get removed after the Transform is processed, but is not allowed when being included (as pure CloudFormation does not permit cycles). To enable cycle processing behavior similar to cloudformation, set allowCyclicalReferences of CfnIncludeProps to true.

When that happens, you should instead download the processed template from the CloudFormation AWS Console (make sure the "View processed template" checkbox is checked in that case):

processed template in the CloudFormation AWS Console

When you include that processed template in your CDK application, running cdk diff will now show a lot of differences with the deployed Stack, because cdk diff uses the unprocessed template by default. To alleviate that problem, you can pass the --processed switch to cdk diff, which will make the diff command compare against the processed template of the deployed Stack, which will give more precise results in this case.

Converting L1 resources to L2 ​

The resources the getResource method returns are what the CDK calls Layer 1 resources (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.

UsingfromCfn*() 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:

ts
declare const cfnTemplate: cfn_inc.CfnInclude;
const cfnKey = cfnTemplate.getResource('Key') as kms.CfnKey;
const key = kms.Key.fromCfnKey(cfnKey);
python
# cfn_template: cfn_inc.CfnInclude

cfn_key = cfn_template.get_resource("Key")
key = kms.Key.from_cfn_key(cfn_key)
java
CfnInclude cfnTemplate;

CfnKey cfnKey = (CfnKey)cfnTemplate.getResource("Key");
IKey key = Key.fromCfnKey(cfnKey);
csharp
CfnInclude cfnTemplate;

var cfnKey = (CfnKey)cfnTemplate.GetResource("Key");
var key = Key.FromCfnKey(cfnKey);
go
var cfnTemplate CfnInclude

cfnKey := cfnTemplate.GetResource(jsii.String("Key")).(CfnKey)
key := kms.Key_FromCfnKey(cfnKey)

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:

ts
declare const cfnTemplate: cfn_inc.CfnInclude;

// using from*Name()
const cfnBucket = cfnTemplate.getResource('Bucket') as s3.CfnBucket;
const bucket = s3.Bucket.fromBucketName(this, 'L2Bucket', cfnBucket.ref);

// using from*Arn()
const cfnKey = cfnTemplate.getResource('Key') as kms.CfnKey;
const key = kms.Key.fromKeyArn(this, 'L2Key', cfnKey.attrArn);

// using from*Attributes()
declare const privateCfnSubnet1: ec2.CfnSubnet;
declare const privateCfnSubnet2: ec2.CfnSubnet;
const cfnVpc = cfnTemplate.getResource('Vpc') as ec2.CfnVPC;
const vpc = ec2.Vpc.fromVpcAttributes(this, 'L2Vpc', {
  vpcId: cfnVpc.ref,
  availabilityZones: core.Fn.getAzs(),
  privateSubnetIds: [privateCfnSubnet1.ref, privateCfnSubnet2.ref],
});
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]
)
java
CfnInclude cfnTemplate;

// using from*Attributes()
CfnSubnet privateCfnSubnet1;
CfnSubnet privateCfnSubnet2;


// using from*Name()
CfnBucket cfnBucket = (CfnBucket)cfnTemplate.getResource("Bucket");
IBucket bucket = Bucket.fromBucketName(this, "L2Bucket", cfnBucket.getRef());

// using from*Arn()
CfnKey cfnKey = (CfnKey)cfnTemplate.getResource("Key");
IKey key = Key.fromKeyArn(this, "L2Key", cfnKey.getAttrArn());
CfnVPC cfnVpc = (CfnVPC)cfnTemplate.getResource("Vpc");
IVpc vpc = Vpc.fromVpcAttributes(this, "L2Vpc", VpcAttributes.builder()
        .vpcId(cfnVpc.getRef())
        .availabilityZones(Fn.getAzs())
        .privateSubnetIds(List.of(privateCfnSubnet1.getRef(), privateCfnSubnet2.getRef()))
        .build());
csharp
CfnInclude cfnTemplate;

// using from*Attributes()
CfnSubnet privateCfnSubnet1;
CfnSubnet privateCfnSubnet2;


// using from*Name()
var cfnBucket = (CfnBucket)cfnTemplate.GetResource("Bucket");
var bucket = Bucket.FromBucketName(this, "L2Bucket", cfnBucket.Ref);

// using from*Arn()
var cfnKey = (CfnKey)cfnTemplate.GetResource("Key");
var key = Key.FromKeyArn(this, "L2Key", cfnKey.AttrArn);
var cfnVpc = (CfnVPC)cfnTemplate.GetResource("Vpc");
var vpc = Vpc.FromVpcAttributes(this, "L2Vpc", new VpcAttributes {
    VpcId = cfnVpc.Ref,
    AvailabilityZones = Fn.GetAzs(),
    PrivateSubnetIds = new [] { privateCfnSubnet1.Ref, privateCfnSubnet2.Ref }
});
go
var cfnTemplate CfnInclude

// using from*Attributes()
var privateCfnSubnet1 CfnSubnet
var privateCfnSubnet2 CfnSubnet


// using from*Name()
cfnBucket := cfnTemplate.GetResource(jsii.String("Bucket")).(CfnBucket)
bucket := s3.Bucket_FromBucketName(this, jsii.String("L2Bucket"), cfnBucket.ref)

// using from*Arn()
cfnKey := cfnTemplate.GetResource(jsii.String("Key")).(CfnKey)
key := kms.Key_FromKeyArn(this, jsii.String("L2Key"), cfnKey.attrArn)
cfnVpc := cfnTemplate.GetResource(jsii.String("Vpc")).(CfnVPC)
vpc := ec2.Vpc_FromVpcAttributes(this, jsii.String("L2Vpc"), &VpcAttributes{
	VpcId: cfnVpc.ref,
	AvailabilityZones: core.Fn_GetAzs(),
	PrivateSubnetIds: []*string{
		privateCfnSubnet1.ref,
		privateCfnSubnet2.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:

    ts
    declare const cfnTemplate: cfn_inc.CfnInclude;
    const param: core.CfnParameter = cfnTemplate.getParameter('MyParameter');
    
    // mutating the parameter
    param.default = 'MyDefault';
    
  • Conditions:

    ts
    declare const cfnTemplate: cfn_inc.CfnInclude;
    const condition: core.CfnCondition = cfnTemplate.getCondition('MyCondition');
    
    // mutating the condition
    condition.expression = core.Fn.conditionEquals(1, 2);
    
  • Mappings:

    ts
    declare const cfnTemplate: cfn_inc.CfnInclude;
    const mapping: core.CfnMapping = cfnTemplate.getMapping('MyMapping');
    
    // mutating the mapping
    mapping.setValue('my-region', 'AMI', 'ami-04681a1dbd79675a5');
    
  • Service Catalog template Rules:

    ts
    declare const cfnTemplate: cfn_inc.CfnInclude;
    const rule: core.CfnRule = cfnTemplate.getRule('MyRule');
    
    // mutating the rule
    declare const myParameter: core.CfnParameter;
    rule.addAssertion(core.Fn.conditionContains(['m1.small'], myParameter.valueAsString),
      'MyParameter has to be m1.small');
    
  • Outputs:

    ts
    declare const cfnTemplate: cfn_inc.CfnInclude;
    const output: core.CfnOutput = cfnTemplate.getOutput('MyOutput');
    
    // mutating the output
    declare const cfnBucket: s3.CfnBucket;
    output.value = cfnBucket.attrArn;
    
  • Hooks for blue-green deployments:

    ts
    declare const cfnTemplate: cfn_inc.CfnInclude;
    const hook: core.CfnHook = cfnTemplate.getHook('MyOutput');
    
    // mutating the hook
    declare const myRole: iam.Role;
    const codeDeployHook = hook as core.CfnCodeDeployBlueGreenHook;
    codeDeployHook.serviceRole = myRole.roleArn;
    

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:

ts
new cfn_inc.CfnInclude(this, 'includeTemplate', {
  templateFile: 'path/to/my/template',
  parameters: {
    'MyParam': 'my-value',
  },
});
python
cfn_inc.CfnInclude(self, "includeTemplate",
    template_file="path/to/my/template",
    parameters={
        "MyParam": "my-value"
    }
)
java
CfnInclude.Builder.create(this, "includeTemplate")
        .templateFile("path/to/my/template")
        .parameters(Map.of(
                "MyParam", "my-value"))
        .build();
csharp
new CfnInclude(this, "includeTemplate", new CfnIncludeProps {
    TemplateFile = "path/to/my/template",
    Parameters = new Dictionary<string, object> {
        { "MyParam", "my-value" }
    }
});
go
cfn_inc.NewCfnInclude(this, jsii.String("includeTemplate"), &CfnIncludeProps{
	TemplateFile: jsii.String("path/to/my/template"),
	Parameters: map[string]interface{}{
		"MyParam": jsii.String("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.

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:

ts
const parentTemplate = new cfn_inc.CfnInclude(this, 'ParentStack', {
  templateFile: 'path/to/my-parent-template.json',
  loadNestedStacks: {
    'ChildStack': {
      templateFile: 'path/to/my-nested-template.json',
    },
  },
});
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"
        )
    }
)
java
CfnInclude parentTemplate = CfnInclude.Builder.create(this, "ParentStack")
        .templateFile("path/to/my-parent-template.json")
        .loadNestedStacks(Map.of(
                "ChildStack", CfnIncludeProps.builder()
                        .templateFile("path/to/my-nested-template.json")
                        .build()))
        .build();
csharp
var parentTemplate = new CfnInclude(this, "ParentStack", new CfnIncludeProps {
    TemplateFile = "path/to/my-parent-template.json",
    LoadNestedStacks = new Dictionary<string, CfnIncludeProps> {
        { "ChildStack", new CfnIncludeProps {
            TemplateFile = "path/to/my-nested-template.json"
        } }
    }
});
go
parentTemplate := cfn_inc.NewCfnInclude(this, jsii.String("ParentStack"), &CfnIncludeProps{
	TemplateFile: jsii.String("path/to/my-parent-template.json"),
	LoadNestedStacks: map[string]CfnIncludeProps{
		"ChildStack": &CfnIncludeProps{
			"templateFile": jsii.String("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, 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:

ts
declare const parentTemplate: cfn_inc.CfnInclude;

const includedChildStack = parentTemplate.getNestedStack('ChildStack');
const childStack: core.NestedStack = includedChildStack.stack;
const childTemplate: cfn_inc.CfnInclude = includedChildStack.includedTemplate;
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
java
CfnInclude parentTemplate;


IncludedNestedStack includedChildStack = parentTemplate.getNestedStack("ChildStack");
NestedStack childStack = includedChildStack.getStack();
CfnInclude childTemplate = includedChildStack.getIncludedTemplate();
csharp
CfnInclude parentTemplate;


var includedChildStack = parentTemplate.GetNestedStack("ChildStack");
var childStack = includedChildStack.Stack;
var childTemplate = includedChildStack.IncludedTemplate;
go
var parentTemplate CfnInclude


includedChildStack := parentTemplate.GetNestedStack(jsii.String("ChildStack"))
childStack := includedChildStack.Stack
childTemplate := includedChildStack.IncludedTemplate

Now you can reference resources from ChildStack, and modify them like any other included template:

ts
declare const childTemplate: cfn_inc.CfnInclude;

const cfnBucket = childTemplate.getResource('MyBucket') as s3.CfnBucket;
cfnBucket.bucketName = 'amzn-s3-demo-bucket1';

const role = new iam.Role(this, 'MyRole', {
  assumedBy: new iam.AccountRootPrincipal(),
});

role.addToPolicy(new iam.PolicyStatement({
  actions: [
    's3:GetObject*',
    's3:GetBucket*',
    's3:List*',
  ],
  resources: [cfnBucket.attrArn],
}));
python
# child_template: cfn_inc.CfnInclude


cfn_bucket = child_template.get_resource("MyBucket")
cfn_bucket.bucket_name = "amzn-s3-demo-bucket1"

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]
))
java
CfnInclude childTemplate;


CfnBucket cfnBucket = (CfnBucket)childTemplate.getResource("MyBucket");
cfnBucket.getBucketName() = "amzn-s3-demo-bucket1";

Role role = Role.Builder.create(this, "MyRole")
        .assumedBy(new AccountRootPrincipal())
        .build();

role.addToPolicy(PolicyStatement.Builder.create()
        .actions(List.of("s3:GetObject*", "s3:GetBucket*", "s3:List*"))
        .resources(List.of(cfnBucket.getAttrArn()))
        .build());
csharp
CfnInclude childTemplate;


var cfnBucket = (CfnBucket)childTemplate.GetResource("MyBucket");
cfnBucket.BucketName = "amzn-s3-demo-bucket1";

var role = new Role(this, "MyRole", new RoleProps {
    AssumedBy = new AccountRootPrincipal()
});

role.AddToPolicy(new PolicyStatement(new PolicyStatementProps {
    Actions = new [] { "s3:GetObject*", "s3:GetBucket*", "s3:List*" },
    Resources = new [] { cfnBucket.AttrArn }
}));
go
var childTemplate CfnInclude


cfnBucket := childTemplate.GetResource(jsii.String("MyBucket")).(CfnBucket)
cfnBucket.bucketName = "amzn-s3-demo-bucket1"

role := iam.NewRole(this, jsii.String("MyRole"), &RoleProps{
	AssumedBy: iam.NewAccountRootPrincipal(),
})

role.AddToPolicy(iam.NewPolicyStatement(&PolicyStatementProps{
	Actions: []*string{
		jsii.String("s3:GetObject*"),
		jsii.String("s3:GetBucket*"),
		jsii.String("s3:List*"),
	},
	Resources: []*string{
		cfnBucket.attrArn,
	},
}))

You can also include the nested stack after the CfnInclude object was created, instead of doing it on construction:

ts
declare const parentTemplate: cfn_inc.CfnInclude;
const includedChildStack = parentTemplate.loadNestedStack('ChildTemplate', {
  templateFile: 'path/to/my-nested-template.json',
});
python
# parent_template: cfn_inc.CfnInclude

included_child_stack = parent_template.load_nested_stack("ChildTemplate",
    template_file="path/to/my-nested-template.json"
)
java
CfnInclude parentTemplate;

IncludedNestedStack includedChildStack = parentTemplate.loadNestedStack("ChildTemplate", CfnIncludeProps.builder()
        .templateFile("path/to/my-nested-template.json")
        .build());
csharp
CfnInclude parentTemplate;

var includedChildStack = parentTemplate.LoadNestedStack("ChildTemplate", new CfnIncludeProps {
    TemplateFile = "path/to/my-nested-template.json"
});
go
var parentTemplate CfnInclude

includedChildStack := parentTemplate.LoadNestedStack(jsii.String("ChildTemplate"), &CfnIncludeProps{
	TemplateFile: jsii.String("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:

ts
import { Construct } from 'constructs';
import * as cfn_inc from 'aws-cdk-lib/cloudformation-include';
import * as path from 'path';

export class MyConstruct extends Construct {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    // include a template inside the Construct
    new cfn_inc.CfnInclude(this, 'MyConstruct', {
      templateFile: path.join(__dirname, 'my-template.json'),
      preserveLogicalIds: false, // <--- !!!
    });
  }
}
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
        )
java
import software.constructs.Construct;
import software.amazon.awscdk.cloudformation.include.*;
import path.*;

public class MyConstruct extends Construct {
    public MyConstruct(Construct scope, String id) {
        super(scope, id);

        // include a template inside the Construct
        // include a template inside the Construct
        CfnInclude.Builder.create(this, "MyConstruct")
                .templateFile(join(__dirname, "my-template.json"))
                .preserveLogicalIds(false)
                .build();
    }
}
csharp
using Constructs;
using Amazon.CDK.CloudFormation.Include;
using Path;

class MyConstruct : Construct
{
    public MyConstruct(Construct scope, string id) : base(scope, id)
    {

        // include a template inside the Construct
        // include a template inside the Construct
        new CfnInclude(this, "MyConstruct", new CfnIncludeProps {
            TemplateFile = Join(__dirname, "my-template.json"),
            PreserveLogicalIds = false
        });
    }
}
go
import "github.com/aws/constructs-go/constructs"
import cfn_inc "github.com/aws/aws-cdk-go/awscdk"
import path "github.com/aws-samples/dummy/path"

type MyConstruct struct {
	Construct
}

func NewMyConstruct(scope Construct, id *string) *MyConstruct {
	this := &MyConstruct{}
	newConstruct_Override(this, scope, id)

	// include a template inside the Construct
	// include a template inside the Construct
	cfn_inc.NewCfnInclude(this, jsii.String("MyConstruct"), &CfnIncludeProps{
		TemplateFile: path.join(__dirname, jsii.String("my-template.json")),
		PreserveLogicalIds: jsii.Boolean(false),
	})
	return this
}

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.

Types ​

NameKindSummary
CfnIncludeConstruct (L1)Construct to import an existing CloudFormation template file into a CDK application.
CfnIncludePropsStructConstruction properties of CfnInclude.
IncludedNestedStackStructThe type returned from CfnInclude.getNestedStack. Contains both the NestedStack object and CfnInclude representations of the child stack.