Experiencing an error message stating 'The token ${Token[TOKEN.72]} is invalid' while using cdk synth, specifically when trying to assign the value of ec2.Vpc.cidr from cfnParameter.value

Attempting to utilize the AWS CDK CfnParameter to parameterize the CIDR value of ec2.Vpc. The aim is to make the stack reusable for VPC creation with the CIDR as a customizable value.

An error stating "${Token[TOKEN.72]} is not valid" occurs during synthesis ($cdk synth) of the stack for the following code snippet:


        // Parameter
        const vpcCidr = new cdk.CfnParameter(this, 'vpcCidr', {
            type: 'String',
            default: "10.0.0.0/16",
            minLength: 10,
            maxLength: 18,
            allowedPattern: '(\\d{1,3})\.(\\d{1,3})\.(\\d{1,3})\.(\\d{1,3})/(\\d{1,2})'
        });

        // VPC Configuration
        const vpc = new ec2.Vpc(this, "vpcName", {
            cidr: vpcCidr.valueAsString,
            maxAzs: 2,
            vpnGateway: true,
            subnetConfiguration: [
                {
                    cidrMask: 19,
                    name: "Private",
                    subnetType: SubnetType.PRIVATE,
                },
                {
                    cidrMask: 20,
                    name: "Public",
                    subnetType: SubnetType.PUBLIC,
                },
                {
                    cidrMask: 21,
                    name: "Protected",
                    subnetType: SubnetType.ISOLATED,
                },
            ],
        });

When passing a static string for the CIDR block, it works fine:


        // VPC Configuration
        const vpc = new ec2.Vpc(this, "vpcName", {
            cidr: "10.0.0.0/16",
            maxAzs: 2,
            vpnGateway: true,
            subnetConfiguration: [
                {
                    cidrMask: 19,
                    name: "Private",
                    subnetType: SubnetType.PRIVATE,
                },
                {
                    cidrMask: 20,
                    name: "Public",
                    subnetType: SubnetType.PUBLIC,
                },
                {
                    cidrMask: 21,
                    name: "Protected",
                    subnetType: SubnetType.ISOLATED,
                },
            ],
        });

Expected behavior: Setting vpcCidr.valueAsString for the CIDR property of ec2.Vpc should work the same as when setting cidr as a direct string value.

Actual error message: ${Token[TOKEN.72]} is not valid. The issue seems to be related to the function in network-util.js:


    /**
     * Converts a string IPv4 to a number
     *
     * Takes an IP Address (e.g. 174.66.173.168) and converts it to a number (e.g., 2923605416); currently only supports IPv4
     *
     * Uses the formula:
     * (first octet * 256³) + (second octet * 256²) + (third octet * 256) +
     * (fourth octet)
     *
     * @param  {string} the IP address (e.g. 174.66.173.168)
     * @returns {number} the integer value of the IP address (e.g., 2923605416)
     */
    static ipToNum(ipAddress) {
        if (!this.validIp(ipAddress)) {
            throw new Error(`${ipAddress} is not valid`);
        }
        return ipAddress
            .split('.')
            .reduce((p, c, i) => p + parseInt(c, 10) * 256 ** (3 - i), 0);
    }

Environment details:

  • AWS CDK CLI Version: 1.3.0

  "dependencies": {
    "@aws-cdk/assert": "^1.2.0",
    "@aws-cdk/aws-ec2": "^1.2.0",
    "@aws-cdk/aws-ram": "^1.2.0",
    "@aws-cdk/core": "^1.2.0"
}
  • Operating System: OSX Mojave
  • Programming Language: Typescript

Answer №1

Regrettably, it appears that the ipToNum function requires parsing and mathematical operations on the CIDR to convert it into a numeric value, making it necessary for the value to be static (known at compile time). Apologies for any inconvenience.

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

Simulating a PubSub publish functionality

I have been trying to follow the instructions provided in this guide on mocking new Function() with Jest to mock PubSub, but unfortunately I am facing some issues. jest.mock('@google-cloud/pubsub', () => jest.fn()) ... const topic = jest.fn( ...

Arrow functions do not function properly with Typescript decorators

I've created a typescript decorator factory that logs the total time taken to execute a function, along with the actual function execution results and parameters passed to the decorator. For example: export function performanceLog(...args: any[]) { ...

Solve the TypeScript path when using jest.mock

I am currently in the process of adding unit tests to a TypeScript project that utilizes compilerOptions.paths. My goal is to mock an import for testing purposes. However, I have encountered an issue where jest is unable to resolve the module to be mocked ...

Using Systemjs to transpile TypeScript async functions

When I manually build .ts files using the tsc tool, I notice that wrappers are generated for async/await keywords. However, I am facing an issue setting up transpile on-the-fly using SystemJS. Here is my index.htm configuration: <script src="https:// ...

Phaser 3 game app on iOS generated with Capacitor lacks audio functionality

I have developed a basic test app using Phaser 3 (written in Typescript and transpiled with rollup) and am utilizing Capacitor to convert it into an iOS application on my Mac. This excerpt highlights the key functionality of the app: function preload () { ...

Adding a constant to a Vue component

Currently working on developing an application using Vue and TypeScript. I'm focused on refactoring some aspects, particularly moving hard-coded strings from a template to a separate constant. What has been implemented is as follows: export const va ...

Angular Back button event not triggering

I'm attempting to redirect the user to a specific URL when they click the back button in their browser. Here is the code snippet: constructor(private router: Router,private location: PlatformLocation) { let eventUrl = window.sessionSt ...

There is an issue with the type candidate in the Notion API, resulting in

In this instance, the troublesome code causing issues is displayed below: import {Client, LogLevel} from "@notionhq/client"; const notion = new Client({ auth: process.env.NOTION_TOKEN, logLevel: process.env.NODE_ENV !== 'product ...

Typescript fails to identify the parameter type of callbacks

I am facing a challenge with the function below and its callback type: type Callbacks = { onSuccess: (a: string) => void; }; function myFunction(event: string, ...args: [...any, Callbacks]) { } The function works correctly except for one issue - ...

Ways to conceal an element in Angular based on the truth of one of two conditions

Is there a way to hide an element in Angular if a specific condition is true? I attempted using *ngIf="productID == category.Lane || productID == category.Val", but it did not work as expected. <label>ProductID</label> <ng-select ...

The specified 'Object' type does not match the required 'Document' constraint

I need assistance with running a MERN application to check for any issues, but I keep encountering this error across multiple files. Error: The 'CatalogType' type does not meet the requirements of 'Document'. The 'CatalogType&apo ...

Is it possible to send requests to multiple APIs using a TypeScript event handler?

I'm facing a challenge in pinging multiple APIs within a single function. It seems like it should be possible, especially since each API shares the same headers and observable. I attempted to write a function for this purpose, but unfortunately, it do ...

Troubleshooting import errors with Typescript for C3 and D3 libraries

I have recently started working on a project using the C3 graphing library within an Ionic2/Angular2 TypeScript setup. After installing C3 via npm and the type definitions via tsd, I imported it into my own TypeScript file like this: import {Component} fr ...

Utilizing interpolation in Angular to apply CSS styling to specific sections of a TypeScript variable

Suppose I have a variable called data in the app.component.ts file of type :string. In the app.component.html file, I am displaying the value of data on the UI using string interpolation like {{data}}. My question is, how can I apply some css to specific ...

Running the NPM build command results in an error specifically related to an HTML file

I encountered an issue in my AngularJS application when running the command: npm run build -- -prod The error message I received was: ERROR in ng:///home/directoryling/appname-play.component.html (173,41): The left-hand side of an arithmetic operation ...

Tips for managing an array of observable items

In my current project, I am working with an Angular application that receives a collection from Firebase (Observable<any[]>). For each element in this collection, I need to create a new object by combining the original value with information from ano ...

Color key in square shape for graph legend

I am looking for legend colors in square shape, but I don't want them to appear as square boxes on the graph. https://i.stack.imgur.com/Of0AM.png The squares are also showing up on the graph, which is not what I want. https://i.stack.imgur.com/Az9G ...

Linking typescript error messages with their respective compiler configurations (tsconfig.json)

Is there a way to identify which compiler option corresponds to a specific Typescript error? While working with Typescript in VSCode, I often encounter errors like initializer provides no value for this binding element. (Please note that these are warnin ...

Error encountered while compiling an Asp.Net Core project due to exceeding the maximum allowable path length in the

Encountering a critical error during the build process with Visual Studio 2016 update 3 Asp.Net Core. The build is interrupted with the following message: Severity Code Description Project File Line Suppression State Error MSB4018 The "FindC ...

Utilize Angular 5 to implement URL routing by clicking a button, while also preserving the querystring parameters within the URL

I have a link that looks like this http://localhost:4200/cr/hearings?UserID=61644&AppID=15&AppGroupID=118&SelectedCaseID=13585783&SelectedRoleID=0 The router module is set up to display content based on the above URL structure { path: & ...