"Obtaining subnet identification using the name or CIDR: A step-by-step

I am seeking help on retrieving the subnet id based on subnet name or cidr in order to deploy a nat gateway. Can someone provide guidance on how to obtain the subnet id? Alternatively, does anyone have any best practices for utilizing typescript functions? Apologies, as I am relatively new to typescript.

export class VpcTestStack extends cdk.Stack {
  svc = 'common';
  env  = 'test';
  cidr = '10.10';
  vpc: ec2.CfnVPC;

constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    this.vpc = new ec2.CfnVPC(this, 'vpc', {
      ...
    });

    this.subnet_creation(this.availabilityZones[0], 'public-01-a', '.0.0/20');
    this.subnet_creation(this.availabilityZones[2], 'public-01-c', '.16.0/20');
    ...
    this.subnet_creation(this.availabilityZones[0], 'private-03-a', '.192.0/20');
    this.subnet_creation(this.availabilityZones[2], 'private-03-c', '.208.0/20');

    this.nat_creation('a', 'public-02-a')
    this.nat_creation('c', 'public-02-c')

  }

  subnet_creation(availability_zone: string, subnet_name: string, subnet_cidr: string) 
  {
    new ec2.CfnSubnet(this, 'subnet-' + subnet_name, {
      availabilityZone: availability_zone,
      cidrBlock: this.cidr + subnet_cidr,
      vpcId: this.vpc.ref,
      tags: [ { key: 'Name', value: this.svc + '-' + this.env + '-' + subnet_name } ]
    });
  }

  nat_creation(az: string, subnet_name: string)
  {
    const natgw_eip = new ec2.CfnEIP(this, 'natgw-eip-' + az, {
      domain: 'vpc'
    });

    new ec2.CfnNatGateway(this, 'natgw-' + az, {
      allocationId: natgw_eip.attrAllocationId,
      subnetId: ???, <---------------------------------------------------------------------- Here
      tags: [ { key: 'Name', value: this.svc + '-' + this.env + '-natgw' + az } ]
    });
  }
}

Answer №1

To extract and reference the subnet that was created, we can use it in a similar way to !Ref in Cloudformation.

const myPublicSubnetOne: ec2.CfnSubnet = this.subnet_creation(
  this.availabilityZones[0],
  "public-01-a",
  ".0.0/20"
);

The method should return the subnet for further usage.

  subnet_creation(
    availability_zone: string,
    subnet_name: string,
    subnet_cidr: string
  ) {
    const subnet = new ec2.CfnSubnet(this, "subnet-" + subnet_name, {
      availabilityZone: availability_zone,
      cidrBlock: this.cidr + subnet_cidr,
      vpcId: this.vpc.ref,
      tags: [
        { key: "Name", value: this.svc + "-" + this.env + "-" + subnet_name },
      ],
    });
    return subnet;
  }

Include the input parameter in your nat_creation function and reference it as subnetId: myPubSubnet.ref,

  nat_creation(az: string, myPubSubnet: ec2.CfnSubnet) {
    const natgw_eip = new ec2.CfnEIP(this, "natgw-eip-" + az, {
      domain: "vpc",
    });
    new ec2.CfnNatGateway(this, "natgw-" + az, {
      allocationId: natgw_eip.attrAllocationId,
      subnetId: myPubSubnet.ref,
      tags: [{ key: "Name", value: this.svc + "-" + this.env + "-natgw" + az }],
    });
  }

Pass the actual subnet object instead of just a string.

this.nat_creation("a", myPublicSubnetOne);

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

The parameter type '(value: any) => any[]' does not match the expected parameter type 'string[]'

I'm encountering an issue where I can't push a value to a state array due to a TS error. Let me highlight the relevant components where the error occurs. The error specifically lies in the child component, within the handleValue(value => [...v ...

Error: The argument provided cannot be assigned to a parameter that requires a string type, as it is currently a number

Currently, I am in the process of migrating some older websites to TypeScript. However, I keep encountering a type error during the build process. The specific error message is Type error: Argument of type 'number' is not assignable to parameter ...

The correct way to add to a string array that has been passed as props to a functional component

There is a parent component that establishes a useState hook with a string array. Then, there is a child component tasked with updating the string array. To accomplish this, both the string array and the useState function are passed to the child component. ...

Is it possible to develop a C equivalent of the typescript Record type?

Is there a way to create a record type equivalent in C like what can be done in TypeScript, and add attributes during runtime? I am aiming to replicate the following: const familyData: string[] = ["paul", "em", "matthias", "kevin"]; const myFamily: Record ...

Error message when using Typescript with Redux Saga: "Cannot use 'then' property on type 'void'. TS2339"

Whenever I attempt to fetch data from this API endpoint using promises, I encounter these type of issues. export function* signUpWithEmail(authInfo: any) { const { email, password } = authInfo.payload try { const response = yield authSignUpService ...

Differentiating functions in Typescript through method overloading by inferring the second argument's type based on the first argument's

Looking to implement method overloading in Typescript with stricter type checking for method invocation based on different arguments. I am encountering an error: 'props' is possibly 'undefined'. This is the code that is causing the e ...

Encountering the error message "Error: 'preserveValueImports' is an unknown compiler option" while setting up a SvelteKit project

https://i.stack.imgur.com/fnidk.png Every time I set up a new sveltekit project using TypeScript, I keep encountering the error "Unknown compiler option 'preserveValueImports'.ts" in the tsconfig.json file. The error shows up above the line wher ...

The function response.body.getReader is not defined

While making a call to a web api using fetch, I encountered an issue when attempting to read the response as a stream. Despite calling getReader() on response.body, I received the error message: "TypeError: response.body.getReader is not a function". ...

The error thrown by Mongoose, stating "TypeError: Cannot read property 'catch' of undefined," is not caught after the data is saved

After updating to Mongoose version 5.0.15, I encountered an error that says TypeError: Cannot read property 'catch' of undefined when trying to save my object with errors found, even though everything was working fine on Mongoose version 4.13.11. ...

Extending Two Classes in Typescript: A Complete Guide

I am looking for a way to efficiently save time by reusing common code across classes that extend PIXI classes within a 2D WebGL renderer library. Object Interfaces: module Game.Core { export interface IObject {} export interface IManagedObject e ...

Using Formik: When the initial value is changed, the props.value will be updated

After the initial props are updated, it is important to also update the values in the forms accordingly. export default withFormik({ mapPropsToValues: (props: Props) => { return ( { id: props.initialData.id, ...

Setting up admin credentials with TypeScript in Firebase cloud functions

While working with Firebase cloud functions in JavaScript, I utilized the following code snippet to initialize admin: admin.initializeApp({ credential: admin.credential.cert(require('./key/firebase-adminsdk.json')), databaseURL: "https://app ...

Having trouble getting webpack to transpile typescript to ES5?

Despite following official guides and various tutorials, I am still facing an issue with compiling my code to ES5 using TypeScript and webpack. The problem is that the final bundle.js file always contains arrow functions. Here is a snippet from my webpack ...

Tips for creating unit tests for my Angular service that utilizes the mergeMap() function?

As a beginner with the karma/jasmine framework, I am currently exploring how to add a test case for my service method shown below: public getAllChassis(): Observable<Chassis[]> { return this.http.get('chassis').pipe( merge ...

Tips for validating Enum Strings using the newest version of Joi?

Is there a way to validate Enum String? In the past, I followed this advice from: https://github.com/hapijs/joi/issues/1449 enum UserRole { Admin = 'admin', Staff = 'staff' } const validator = { create: Joi.object().keys({ ...

Typescript is throwing a fit over namespaces

My development environment consists of node v6.8.0, TypeScript v2.0.3, gulp v3.9.1, and gulp-typescript v3.0.2. However, I encounter an error when building with gulp. Below is the code snippet that is causing the issue: /// <reference path="../_all.d. ...

``Is it possible to iterate through a collection of objects using a loop?

I am facing an issue with updating a global array that contains objects, where each object includes another array. My goal is to update the main array with values from the arrays within the objects following a specific logic! generalArray = [{name:String, ...

Expressjs makes it easy to upload audio files to your website

Currently, I'm developing a music app and I'm looking for the best way to upload an audio file in my ExpressJS application. Is it possible to use Cloudinary or is there another method that is more efficient? I attempted to follow the same proces ...

Unexpected behavior with onKeyPress in React-Native Windows resulting in missing key press events

Currently, I am working on a Windows app using react-native version 0.54.0. For one of the functionalities, I have incorporated a TextInput element and would like to use onKeyPress. Here is my code snippet: <TextInput ref = { this.setTextInputRef } on ...

Automated Import Feature in Visual Studio Code

I'm currently transitioning from Webstorm to Visual Studio Code due to the poor performance of Webstorm. However, I'm facing issues with Visual Studio Code not being very efficient at detecting and importing the dependencies I need. I find mysel ...