Is there a way to seamlessly transfer (optional) parameters from a CloudFormation template to a CDK resource within a CfnInclude without statically defining the list of parameters?

Trying to grasp these syntax rules, unsure if it's possible.

We have numerous CloudFormation templates that we want to deploy using CDK by constructing them with CfnInclude. The issue is that CfnInclude always needs an explicit parameters argument if parameters are involved.

Is there a way to write this in a more general manner? So we can create multiple resources via CfnInclude in just one loop for all the CF templates, each possibly having different parameters or none at all. Otherwise, I'd have to provide all potential parameters to all CF templates and specify them during CfnInclude.

The values of actual parameters come from another source and are stored in a map. Let's say that, altogether, these CF templates may require 0, 1, 2, or 3 possible parameters from a list like this:

        let cfnParameters = {
            "param1": value1,
            "param2": value2,
            "param3": value3,
        };

Can we somehow, by providing the template files, instruct CDK to automatically determine the number and type of parameters for each file, then replace them with the proper values from the map (essentially passing a dynamically created Parameters list for each template)? It seems like the getParameters API only works on the fully constructed CF template after CfnInclude has been used?

And is it not possible to first create a CfnInclude without supplying the Parameters, then use GetParameters and substitute them with actual values afterward? The documentation indicates that Parameter Replacement can only occur during construction time?

Answer №1

It's important to ensure that CfnInclude has the correct keys in the parameters prop to avoid errors. Simply create a parameter replacement map based on the template file before initializing CfnInclude. This involves reading the template file, mapping its keys to desired values, and passing the resulting map to CfnInclude.

// MyTemplateIncluder.ts

// Define values to be applied
const parameters = {
  InstanceType: 'm1.large',
  KeyName: 'my-key-name',
  SSHLocation: '0.0.0.0/0',
  AnotherKey: 'anotherValue',
};

// Read the template file
const templatePath = path.join(__dirname, 'template.json');
const file = fs.readFileSync(templatePath, 'utf-8');
const templateParams = JSON.parse(file)?.['Parameters'] ?? {};

// Create a new object with keys from the template and values from parameters
const replacementParameters = Object.keys(templateParams).reduce((acc, curr) => {
  acc[curr] = parameters[curr];
  return acc;
}, {});

new include.CfnInclude(this, 'MyTemplate', {
  templateFile: templatePath,
  parameters: replacementParameters,
});

This logic can be modularized by encapsulating it in a reusable subclass of Construct, which accepts parameter values and the template filename as props.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Include additional information beyond just the user's name, profile picture, and identification number in the NextAuth session

In my Next.js project, I have successfully integrated next-auth and now have access to a JWT token and session object: export const { signIn, signOut, auth } = NextAuth({ ...authConfig, providers: [ CredentialsProvider({ async authorize(crede ...

Troubleshoot an Office add-in using VS Code

Looking for guidance on Office add-ins and VS code... I recently went through the steps outlined in this tutorial by Microsoft to create an Excel custom functions add-in. To debug it using VS code, I had to select TypeScript as the script type while creat ...

What steps should I take to troubleshoot this Angular issue within a Visual Studio 2022 project that utilizes the Standalone Angular template?

After going through this tutorial and meticulously following each step, I encountered an error when trying to run the application: https://i.sstatic.net/EvYgg.jpg Can anyone advise on how to resolve this issue? I'm facing a similar error while attem ...

The execution time of Node's Promises.all() function is unreasonably slow

I need to add a table containing data on sent emails after each email has been successfully sent. Within a loop, I am populating an array to be resolved using the Promise.all(). insertData is a function that adds data, requiring two parameters: connector, ...

typescript: Imported modules in typescript are not functioning

I'm facing an issue where I installed the 'web-request' module but unable to get it working properly. Here is my code: npm install web-request After installation, I imported and used it in my class: import * as WebRequest from 'web-r ...

React Typescript Mui causing `onBlur` event to trigger with every change occurring

I'm currently developing a front-end application using Typescript and React with MUI. The form code I have written is as follows: <TextField label="Password" value={this.state.password} placeholder="Choose a password" type="password" onC ...

Uploading Files through Reactive Forms in Angular

I tried following a tutorial on integrating file upload functionality into my reactive form, which can be found at the following link: . However, I've encountered an issue where I'm getting an error message stating "this.onChange is not a functio ...

The compatibility issues between Karma and Jasmine testing configurations cause errors during the Ionic packaging process

I've recently added testing to my ionic app using karma + jasmine, along with a typescript pre-processor. Below are the dependencies I have, most of which were added specifically for testing: "devDependencies": { "@ionic/app-scripts": "1.0.0", ...

Create an interactive and responsive user interface for Object using the Angular framework

After receiving a JSON Object from an API call with multiple string values, I need to create an Interface for this Object in the most efficient way possible. Rather than manually writing an Interface with 100 keys all of type string, is there a quicker a ...

React-Redux: Unable to access the 'closed' property as it is undefined

Encountered a problem when using dispatch() in React-Redux. Specifically, the action below: export const fetchMetrics = () => { dispatch(fetchMetricsBegin); APIService.get('/dashboard/info/') .then((response) => { ...

Creating mandatory reactive form fields in Angular 11's HTML code based on conditions

I am facing an issue with two select/dropdown fields in my form. The second dropdown field should render based on a condition *ngIf="selectedStdntList?.packages". However, the problem is that the submit form function stops working even when the c ...

Using the typescript infer feature does not function properly when dealing with arrays

My TypeScript code is causing some unexpected results: const myObject = { foo: ['a', 'b', 'c'] } type MyType = typeof myObject.foo extends [...infer Content] ? string : boolean The type MyType is coming out as 'string ...

Struggling with Primeng's KeyFilter functionality?

I've implemented the KeyFilter Module of primeng in my project. Check out the code snippet below: <input type="text" pInputText [(ngModel)]="price.TintCost" [pKeyFilter]="patternDecimal" name="tintCost" required="true" /> Take a look at my Typ ...

Can you explain the correct method for assigning types when destructuring the `callbackFn.currentValue` in conjunction with the `.reduce()` method? Thank you

I'm working with an array of arrays, for example: const input = [['A', 'X'], ['B', 'Y'],...]; In addition to that, I have two enums: enum MyMove { Rock = 'X', Paper = 'Y', Scis ...

What is the role of @Output and EventEmitter in Ionic development?

I'm currently working on integrating Google Maps and Firebase database. My goal is to save my location in the Firebase database and transfer data using @Output and eventEmitter. However, I am facing an issue where pickedLocation has a value but this.l ...

How to send a dynamic URL parameter to a function in Next.js TypeScript without using implicit typing

When utilizing the useRouter function with a parameter of type string, the following error is encountered: Type 'string | string[] | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type & ...

Learn how to effortlessly move a file into a drag-and-drop area on a web page with Playwright

I am currently working with a drag-zone input element to upload files, and I am seeking a way to replicate this action using Playwright and TypeScript. I have the requirement to upload a variety of file types including txt, json, png. https://i.stack.img ...

Securing Email and Password Data in Cypress Tests

Greetings! I trust everyone is in good spirits. My dilemma lies in the fact that I am hesitant to include email and passwords in version control. I am considering using environment variables in my cypress tests and utilizing secrets for runtime value pro ...

Angular 2+ encountering an internal server error (500) while executing an http.post request

Here is my service function: public postDetails(Details): Observable<any> { let cpHeaders = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: cpHeaders }); return this.htt ...

Best practice for incorporating the cq-prolyfill third-party JavaScript library into an Angular 5 application

I'm experiencing an issue with the cq-prolyfill library not functioning properly when included through a typescript import statement within an angular module. I have confirmed that it is included in my vendor bundle, but for some reason the initial se ...