Providing Parameters to CfnInclude with CDK

Recently on a project, my team decided to migrate from using YAML files for our Cloudformation stack to using AWS Cloud Development Kit. We made this switch so we could more easily create and update our stack using TypeScript. Our existing YAML referenced some parameters that we kept alongside it in JSON files. As part of our migration process, here’s how we provided those parameters to our new stack with CfnInclude.

Prerequisites

To provide parameters via CDK to your existing Cloudformation YAML, we’ll assume you’ve already migrated to CDK and are now using CfnInclude. To do this, we followed Amazon’s handy guide for migrating in combination with another tutorial.

The code for defining your stack should look something like this:


// app.ts
import * as cfnInclude from "@aws-cdk/cloudformation-include";
import * as cdk from "@aws-cdk/core";

const app = new cdk.App();
const stack = new cdk.Stack(app, "wrapper-stack", {
  env,
  stackName: “my-wrapper-stack”,
});

new cfnInclude.CfnInclude(stack, "included-template", {
  templateFile: path.join(process.cwd(), "cfn", “cloudformation-template.yml"),
});

Note: this guide will assume a project structure similar to this:


aws-infrastructure/
- bin/
  - app.ts
- cfn/
  - cloudformation-template.yml
- cdk.json
- package.json
- tsconfig.json

Providing Parameters

To provide parameters, we simply need to update our CfnInclude to pass in parameters as a prop alongside templateFile. You should pass the parameters in as key-value pairs.


new cfnInclude.CfnInclude(stack, "included-template", {
  templateFile: path.join(process.cwd(), "cfn", "cloudformation-template.yml"),
  parameters: {
	myKey: “my-value”
	},
});

We can pass in our parameters directly like this, or we can reference values in the context section of our cdk.json.

Let’s say we have our cdk.json set up as follows:


// cdk.json
{
  "app": "npx ts-node --prefer-ts-exts bin/app.ts",
  ...,
  "context": {
	...,
	“params”: {
		“myKey”: “my-value”
		}
	}
}

If we want to get the params from the context, we can use this line:


const params = app.node.tryGetContext(“params”);

From this, we’ll use our key to access the value we want from the params object. Finally, we can pass that same key and our retrieved value to CfnInclude.


const params = app.node.tryGetContext(“params”);
new cfnInclude.CfnInclude(stack, "included-template", {
  templateFile: path.join(process.cwd(), "cfn", "cloudformation-template.yml"),
  parameters: {
	myKey: params[“myKey”]
	},
});

With this setup, our Cloudformation YAML file will consume the parameters provided and apply them to the template.