Using TypeScript to define task invocation parameters with AWS CDK's CfnMaintenanceWindowTask

Currently, I am utilizing AWS CDK along with the library @aws-cdk/aws-ssm and TypeScript to construct CfnMaintenanceWindowTask. The code example I am working on is derived from AWS CloudFormation documentation, specifically for "Create a Run Command task that targets instances using a maintenance window target ID". Here is an excerpt of the JSON CloudFormation code that I am endeavoring to convert into CDK format:

"TaskInvocationParameters": {
                "MaintenanceWindowRunCommandParameters": {
                    "Parameters": {
                        "Operation": [
                            "Install"
                        ],
                        "RebootOption": [
                            "NoReboot"
                        ]
                    }
                }

In my CfnMaintenanceWindowTask object, I aim to define the property taskInvocationParameters using TypeScript code provided below. The challenge arises when attempting to do so due to the error encountered for the property taskInvocationParameters:

"TS2322: Type '{ maintenanceWindowRunCommandParameters: { Parameters: { Operation: string[]; BaselineTags: { key: string; values: string[]; }[]; RebootOption: string[]; }[]; }[]; }' is not assignable to type 'IResolvable | TaskInvocationParametersProperty | undefined'."

While I suspect there might be issues with my implementation, I am unable to pinpoint the exact problem area.

const maintenanceWindowRunCommandParametersWindowsParametersBaselineTags = {
            key: 'PatchBaseline',
            values: [
                'Windows-Server-CritImp-7app-CDK'
            ]
        };    

const maintenanceWindowRunCommandParametersWindowsParameters = {
            Operation: [
                'Install'
            ],
            BaselineTags:[
                maintenanceWindowRunCommandParametersWindowsParametersBaselineTags
            ],
            RebootOption: [
                'NoReboot'
            ]
        };

const maintenanceWindowRunCommandParametersWindows = {
            Parameters: [
                maintenanceWindowRunCommandParametersWindowsParameters
            ],
        };    

const taskInvocationParametersRunPatchBaselineAssociationWindows = {
                maintenanceWindowRunCommandParameters: [
                    maintenanceWindowRunCommandParametersWindows
                ]
            };
    
    const maintenanceWindowTaskWindowsServer = new ssm.CfnMaintenanceWindowTask(this, 'Maintenance-task-Windows-CDK',{
                name: 'Maintenance-task-Windows-CDK',
                priority: 0,
                maxConcurrency: '2',
                maxErrors: '2',
                taskType: 'RUN_COMMAND',
                taskArn: 'AWS-RunPatchBaselineAssociation',
                taskInvocationParameters: taskInvocationParametersRunPatchBaselineAssociationWindows,
                windowId: maintenanceWindowEveryDayScanOnly.ref,
                targets: [
                    maintenanceWindowTaskWindowsServersTargets
                ]
            });

UPDATE

Upon implementing the code shared by @Hcaertnit, I encountered the following error post-deployment.

Failed resources: 10:42:06 | CREATE_FAILED | AWS::SSM::MaintenanceWindowTask | Maintenance-task-Windows-CDK (MaintenancetaskWindowsCDK) Cannot deserialize instance of java.lang.String out of START_OBJECT token at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.amazonaws.services.ssm.model.RegisterTaskWithMaintenanceWindowRequest["TaskInvocationParameters"]->com.amazonaws.services.ssm.model.MaintenanceWindowTaskInvoc ationParameters["MaintenanceWindowRunCommandParameters"]->com.amazonaws.services.ssm.model.MaintenanceWindowRunCommandParameters["Parameters"]->java.util.LinkedHashMap["BaselineTags"]->java.util.ArrayList[0])

Answer №1

Combine your initial variables into a single object as shown below:

const taskInvocationParametersRunPatchBaselineAssociationWindows = {
    maintenanceWindowRunCommandParameters: {
        parameters: {
            Operation: ["Install"],
            BaselineTags: [
                {
                    key: "PatchBaseline",
                    values: ["Windows-Server-CritImp-7app-CDK"],
                }
            ],
            RebootOption: ["NoReboot"],
        },
    },
};
  1. maintenanceWindowRunCommandParameters
    requires an object as input; you were passing it an array with an object inside.
  2. The object includes a parameters property (not Parameters), which is itself an object. You correctly included the inner object within an array for this property.

I consolidated the variables to enhance readability, as lengthy variable names can become cumbersome to manage.

Answer №2

The issue:

Error in resources: 10:42:06 | CREATE_FAILED | AWS::SSM::MaintenanceWindowTask | Maintenance-task-Windows-CDK (MaintenancetaskWindowsCDK) Unable to deserialize instance of java.lang.String from START_OBJECT token at [Source: UNKNOWN; line: -1, column: -1]

This error was triggered by incorrectly implemented BaselineTags parameter within the AWS-RunPatchBaselineAssociation run command. Below is the definition for this parameter.

"BaselineTags": {
      "type": "String",
      "description": "(Optional) The baseline tags to use during the patching operation.",
      "allowedPattern": "(^$)|^Key=(.){1,256},Values=(.){0,256}[^,]$",
      "default": ""
    },

To rectify this, the code should follow this format:

const maintenanceWindowTaskWindowsServer = new ssm.CfnMaintenanceWindowTask(this, 'Maintenance-task-Windows-CDK',{
            name: 'Maintenance-task-Windows-CDK',
            description: 'Maintenance windows task used for Windows Servers.',
            priority: 0,
            maxConcurrency: '2',
            maxErrors: '2',
            taskType: 'RUN_COMMAND',
            taskArn: 'AWS-RunPatchBaselineAssociation',
            taskInvocationParameters: {
                maintenanceWindowRunCommandParameters: {
                    parameters: {
                        Operation: ["Install"],
                        BaselineTags: ["Key=PatchBaseline,Values=Windows-Server-CritImp-7app-CDK"],
                        RebootOption: ["NoReboot"]
                    }
                }
            },
            windowId: maintenanceWindowEveryDayScanOnly.ref,
            targets: [
                {
                    key: 'WindowTargetIds',
                    values: [
                        maintenanceWindowTargetWindowsServer.ref
                    ]
                }
            ]
        });

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

What is the best way to initialize a discriminated union in TypeScript using a given type?

Looking at the discriminated union named MyUnion, the aim is to invoke a function called createMyUnionObject using one of the specified types within MyUnion. Additionally, a suitable value for the value must be provided with the correct type. type MyUnion ...

next-intl failing to identify the primary language setting

When testing next-intl for the app directory in the Next.js v13.4.0, I encountered an issue where the default locale was not recognized. Despite following the documentation step by step, I also faced significant challenges with the client-side version in p ...

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...

Typescript: create a type similar to keyof but with a particular value type

I have an interface called MyInterface interface MyInterface { field1: boolean, field2: MyType, field3: MyType } In this interface, I want to create a new type that contains only the keys which have values of type MyType. While I know about the key ...

Seamlessly incorporating Storybook with Tailwind CSS, Create Next App, and TypeScript

*This is a new question regarding my struggles with integrating Storybook and Tailwind CSS. Despite following the recommended steps, I am unable to make Tailwind work within Storybook. Here's what I've done: I started a TypeScript project from s ...

What type of event does the Input element in material-ui v1 listen for?

I'm currently grappling with material-ui v1 as I search for the appropriate event type for input elements. Take a look at the code snippet below: <Select value={this.numberOfTickets} onChange={this.setNumberOfTickets}> .... Here is the impleme ...

Is it possible to create an instance in TypeScript without using class decorators?

As per the definition on Wikipedia, the decorator pattern enables you to enhance an object of a class with additional functionalities, such as: let ball = new BouncyBall(new Ball()) The Ball object is adorned with extra features from the BouncyBall class ...

An issue has been identified with React's HTML input maxLength feature where it does not display an error

Within my form, I have an input field that currently does not include validation for a maximum length. <input type="text" className="form-control" id="company" onBlur= ...

How to incorporate a popup modal in your project and where should you place the DialogService constructor

Currently, I am in the process of developing a CRUD ASP.NET Core application using Angular 2 and Typescript. Prior to incorporating a popup feature, this was my output: https://i.stack.imgur.com/vHvCC.png My current task involves placing the "Insert or e ...

Clear drop down selections after button is pressed

I am currently working with a grid in my template that contains multiple dropdowns, each row having its own. When I click a button, I gather the values from these dropdowns. However, upon clicking this button, I wish to reset all the dropdowns back to thei ...

Loading dynamic content within Angular Material tabs allows for a more customized and interactive user experience

I am currently working on creating a dynamic tab system using Angular Material: Tabs. I have encountered an issue with loading content on tabs after the initial one, where the functionality only works when the first tab is loaded. Below you can see the ta ...

Unlawful use of Unicode characters

I am currently experiencing an issue while attempting to upload the document.sdf (json) file to Amazon Cloud Search. Everything works seamlessly until certain special characters are encountered. Encountered Unicode characters that are not compliant with C ...

substitute one item with a different item

I am facing an issue with updating the address object within an organization object. I receive values from a form that I want to use to update the address object. However, when I try to change the address object in the organization using Object.assign, i ...

AWS Cognito User Pools Event Trigger Object

Looking to create a unique verification message for new users registered in my AWS Cognito User Pool. I'm attempting to link a Lambda function with a "Custom message" trigger to achieve this. The challenge lies in identifying the exact format of the ...

Managing numerous subscriptions to private subjects that are revealed by utilizing the asObservable() method

I'm using a familiar approach where an Angular service has a private Subject that provides a public Observable like this: private exampleSubject = new Subject<number>(); example$ = this.exampleSubject.asObservable(); In my particular situation, ...

Refreshing the Mat Dialog content when removing items in Angular Material

I have successfully implemented a mat dialog table with 3 columns - name, email, and delete icon. When the user clicks on the delete icon, it prompts a confirmation message to confirm the deletion. Upon confirming, the item is removed from the database. Ho ...

The error message "Type 'Dispatch<SetStateAction<undefined>>' cannot be assigned to type 'Dispatch<SetStateAction<MyType | undefined>>'" appears in the code

I'm encountering challenges while creating a wrapper for useState() due to an unfamiliar error: Type 'Dispatch<SetStateAction>' cannot be assigned to type 'Dispatch<SetStateAction<VerifiedPurchase | undefined>>' ...

Error in React-Typescript: The element type 'Component' is missing any construction or call signatures

I recently wrote a higher order component using React withContext: import React from 'react'; import permissionContext from 'context'; interface Props { Component: () => React.Component; } const withContext: React.FC<Props> ...

Zod data structure featuring optional fields

Is there a more efficient way to define a Zod schema with nullable properties without repeating the nullable() method for each property? Currently, I have defined it as shown below: const MyObjectSchema = z .object({ p1: z.string().nullable(), p2 ...

What steps should I take to create a React component in Typescript that mimics the functionality of a traditional "if" statement?

I created a basic <If /> function component with React: import React, { ReactElement } from "react"; interface Props { condition: boolean; comment?: any; } export function If(props: React.PropsWithChildren<Props>): ReactElement | nul ...