Checking for the existence of a custom VPC within AWS CDK: A comprehensive guide

While working on a CDK script, I encountered a situation where I needed to utilize the default VPC. Here is the code snippet for that:

vpc = ec2.Vpc.fromLookup(this, "UseDefaultVPC", {
  isDefault: true
});

In case I need to use an existing non-default VPC, I have this piece of code (which searches based on existing tags):

vpc = ec2.Vpc.fromLookup(this, "UseCustomVPCAlreadyCreated", {
  tags: {
    environment: project.environment,
    project_name: project.name
  }
});

The requirement is that the VPC should be created the first time and then reused upon update. It needs to work like this:

Attempt to use an existing VPC, if not found, create one

try {
  vpc = ec2.Vpc.fromLookup(this, "UseCustomVPCAlreadyCreated", {
    tags: {
      environment: project.environment,
      project_name: project.name,
    },
  });
  console.log("Using a custom VPC: ", vpc.vpcId);
} catch (error) {
  vpc = new ec2.Vpc(this, "CreateNewVPC", {
    cidr: "10.0.0.0/16",
    maxAzs: 99, // 99 to use all AZs
  });
  console.log("VPC does not exist, creating it: ", vpc.vpcId);
}

However, the try-catch block is not functioning as expected. The output shows:

It tries twice and fails to hit the catch block:

$ cdk deploy --profile fagianijunior
Using a custom VPC:  vpc-12345
Using a custom VPC:  vpc-12345
[Error at /WordpressStack] Could not find any VPCs matching {"account":"NNNNNNNNNNNN","region":"us-east-1","filter":{"tag:environment":"staging","tag:project_name":"wordpress"},"returnAsymmetricSubnets":true}
Found errors

Answer №1

There is no need for you to manually check if the VPC already exists in AWS when creating it. The system automatically verifies this using the identifier provided as the second argument. If a VPC with the same ID is found, it will be updated with any changes you specify. If there is no existing VPC with the given ID, a new one will be created. Essentially, all you have to do is define the desired state and let AWS handle the rest by creating new instances, updating existing ones, or leaving them unchanged if no modifications are needed.

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

Creating the option for nested type properties to be optional

Working with auto generated types from a library poses a challenge for me. The types currently have all values as required, but I would like to mark some of them as optional. While I know this can be achieved using generics in typescript, I am unsure about ...

Leverage the power of function overloading in TypeScript for efficient code

How can function overloading be reused effectively in TypeScript? Consider a scenario where a function is overloaded: function apply(value: number): number; function apply(value: string): string; function apply(value: any): any { return value; } No ...

Enhancing responsiveness in the auto-suggest feature

I am struggling to update the added value in the DOM after pushing a new element into the array of options. Despite my efforts, the update is not reflecting in the DOM. import { Component, OnInit } from '@angular/core'; import { FormControl } fro ...

What are some creative ways to emphasize certain dates?

Is there a way to customize mui-x-date-pickers to highlight specific days from a Date array with green filled circles around them? I am using new Date and wondering how to achieve this effect. Below is the code snippet I am currently working with: <Dat ...

Retrieve the object from the data received from the HTTP GET API call

I have a question that has been asked before, but I am unable to achieve the desired result with my current approach. When my service retrieves data from an API, it returns results in the following format: { "nhits": 581, "paramete ...

The use of the .reset() function in typescript to clear form data may lead to unexpected

I've been trying to use document.getelementbyID().reset(); to reset form values, but I keep running into an error in TypeScript. Property 'reset' does not exist on type 'HTMLElement'. Here's how I implemented it: const resetB ...

Using JSON.stringify() for custom serialization of an object

Imagine there is an object called a with properties: const a = { foo: 123, bar: 'example' } Now, this object is a part of another object called b like this: const b = { a: a, anotherField: "example" } While working with TypeScript, th ...

Embed the getServerSideProps function within a helper method

I have multiple pages that require protection using firebase admin methods: const getServerSideProps = async (ctx: GetServerSidePropsContext) => { try { const cookies = nookies.get(ctx); const token = await firebaseAdmin.auth().verifyIdToken(c ...

Steps for importing Typescript-exporting libraries in next.js

Encountering a challenge while attempting to import a component from a private library that exports Typescript, we are met with the following error message: Module parse failed: Unexpected token (82:7) You may need an appropriate loader to handle this file ...

In TypeScript, if all the keys in an interface are optional, then not reporting an error when an unexpected field is provided

Why doesn't TypeScript report an error when an unexpected field is provided in an interface where all keys are optional? Here is the code snippet: // This is an interface which all the key is optional interface AxiosRequestConfig { url?: string; m ...

Is there a way to determine the specific child property types of a custom Generic type extension?

I am looking to create a function that can retrieve a property from an extended generic type. Is this something achievable? Here is my attempt: interface Animal { readonly weight: {total: number} } interface Dog extends Animal { readonly weight: ...

A guide on renewing authentication tokens in the Nestjs framework

import { ExtractJwt, Strategy } from 'passport-jwt'; import { AuthService } from './auth.service'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common&apo ...

Is it possible to define a constant enum within a TypeScript class?

I am looking for a way to statically set an enum on my TypeScript class and be able to reference it both internally and externally by exporting the class. As I am new to TypeScript, I am unsure of the correct syntax for this. Below is some pseudo-code (whi ...

How can we import the entire Jasmine library using CucumberJS?

I am currently trying to implement unit testing using Jasmine and CucumberJS in my Angular v9 application. I have followed the tutorial provided by cucumber.io to set up cucumber as the default runner. However, I am facing difficulties in using Jasmine met ...

What is the best way to send file data as a response from an express route in NodeJS?

I have a local JSON file structured as follows: { license: "abcd", name: "abcd", data: [ Array of JSON Objects .... ] } I am attempting to access the data array within the object and send it as a response from an Exp ...

How to set the type of an object property to a string based on a string from an array of strings in TypeScript

Great { choices: ['Bob', 'Chris', 'Alice'], selectedChoice: 'Alice', } Not So Good { choices: ['Bob', 'Chris', 'Alice'], selectedChoice: 'Sam', } I've been exp ...

Display a separate component within a primary component upon clicking a button

Looking to display data from a placeholder module upon component click. As a beginner with React, my attempts have been unsuccessful so far. I have a component that lists some information for each element in the module as a list, and I would like to be ab ...

The type 'ElementClass' is lacking several key properties, specifically context, setState, forceUpdate, props, and refs

I'm currently developing a web application using NextJS with Typescript. During my testing phase with Jest+Enzyme, I encountered the following error message: ** Test suite failed to run TypeScript diagnostics (customize using `[jest-config].globals. ...

Exploring the concept of type inheritance in TypeScript

I am working on developing various components for an app, each with its own specific structure. The general structure is defined as COMPONENT. Within this framework, there are two distinct components: HEADING and TEXT. These components should be subclasses ...

Is there a way to reset the selected value of a specific option in Mat-Select?

Using mat-select, I need to reset the selection for a specific value of mat-select's mat-option. For instance, take a look at this example on StackBlitz In the example, the mat-select has three options; when selecting Canada, it should revert back t ...