Learn how to dynamically obtain AWS subnet and security group IDs using the serverless framework

I have been utilizing the Serverless Framework to deploy a Lambda function to AWS using Typescript. When connecting the Lambda to an existing VPC, it is necessary to specify the Subnet and Security Group IDs.

  1. Is there a method to obtain these values dynamically for my cloud account?
  2. Is it secure to store these actual IDs in a git repository, although I prefer not to do so?

index.ts displayed below:

import user from './schema'
import { handlerPath } from '@libs/handler-resolver'

export default {
  handler: `${handlerPath(__dirname)}/handler.createuser`,
  events: [
    {
      http: {
        method: 'post',
        path: 'user',
        request: {
          schemas: {
            'application/json': user,
          },
        },
      },
    },
  ],
  vpc: {
    subnetIds: [
      'subnet-1_ID',
      'subnet-2_ID',
      'subnet-3_ID',
    ], // Remember to replace with your actual Subnet IDs
    securityGroupIds: ['sg-1_ID'], // Remember to replace with your actual Security Group ID
  },
}

Answer №1

Have you set up your Subnets and Security groups with CloudFormation? If so, you can extract them from the CloudFormation stack and directly reference them in your serverless configuration. More details available here.

If not, you can retrieve them using the AWS CLI and either define them as environment variables or pass them in as parameters. Then you can easily call upon them within the serverless configuration.

Below are some commands you can use to obtain the IDs. Make sure your region is correctly configured and run each command for every value needed:

Security Groups:

aws ec2 describe-security-groups --filters Name=tag:Name,Values=<<REPLACE_WITH_NAME_OF_SECURITY_GROUP>> --query "SecurityGroups[*].GroupId" --output text

Subnets (Using the existing VPC ID):

aws --region us-east-1 ec2 describe-subnets --filter Name=vpc-id,Values=<<REPLACE_WITH_VPC_ID>> --query "Subnets[*].SubnetId"

The subnet command will list all subnets associated with that VPC. For specific ones, make sure to tag them accordingly and filter based on those tags. Personally, I recommend leveraging CloudFormation for a smoother process.

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 Angular 2 application functions perfectly when running locally, but encounters issues when running on an ec2 instance

When trying to upload an Angular 2 application to an AWS EC2 t2.small instance, it is not working as expected, even though it runs successfully in a local server. Node version: v7.0.0 NPM version: 3.10.8 There has been an EXCEPTION: Uncaught (in prom ...

Error message in Angular 2 RC-4: "Type 'FormGroup' is not compatible with type 'typeof FormGroup'"

I'm currently facing an issue with Angular 2 forms. I have successfully implemented a few forms in my project, but when trying to add this one, I encounter an error from my Angular CLI: Type 'FormGroup' is not assignable to type 'typeo ...

Angular Error: Unable to access properties of null (specifically 'validators')

I am encountering an issue with my Angular code where I receive the error message "TypeError: Cannot read properties of null (reading '_rawValidators')". import { Component, OnInit } from '@angular/core'; import { Wifi } from './wi ...

Tips for managing errors when using the mergeMap feature in Angular's Typeahead search

Currently working on implementing Typeahead search functionality using API data. When we input valid data, the autosuggestions work correctly. However, if we input invalid data, we receive an error message. The issue arises when trying to input valid dat ...

`Next.js: Addressing synchronization issues between useMemo and useState`

const initializeProjects = useMemo(() => { const data: ProjectDraft[] = t('whiteLabel.projects', {returnObjects: true}) const modifiedData: ProjectWL[] = data.map((item, index) => { return { ... ...

The .env file setting does not take precedence over the default value in the

I am facing an issue with my JSON file that contains the default convict configuration. Here is a simplified version of the file: { "env": { "doc": "The application environment.", "format": [" ...

What is the best way to organize a collection of objects by a specific characteristic in Typescript?

Imagine you have an array of objects with the following structure: type Obj = { id: number, created: Date, title: string } How can you effectively sort this array based on a specific property without encountering any issues in the type system? For ...

Tips for testing a mapbox popup using jasmine testing?

I encountered an issue with my mapbox popup while using jasmine and attempting to write a unit test for it. Here is the function in question: selectCluster(event: MouseEvent, feature: any) { event.stopPropagation(); this.selectedCluster = {geo ...

The variable 'data' is not a property of the type 'any[]'

I am currently facing an issue with a dummy service I created to fetch dummy data. When calling this service from a component ts file, I encountered the following error. After searching through some similar posts, I still haven't been able to resolve ...

What is the correct way to define the onClick event in a React component?

I have been encountering an issue while trying to implement an onClick event in React using tsx. The flexbox and button are being correctly displayed, but I am facing a problem with the onClick event in vscode. I have tried several ideas from the stack com ...

When using TypeScript, it is important to ensure that the type of the Get and Set accessors for properties returning a

Why is it necessary for TypeScript to require Get/Set accessors to have the same type? For example, if we want a property that returns a promise. module App { export interface MyInterface { foo: ng.IPromise<IStuff>; } export int ...

Unable to stop at breakpoints using Visual Studio Code while starting with nodemon

VSCode Version: 1.10.2 OS Version: Windows 7 Profesionnal, SP1 Node version: 6.10.0 Hey there. I'm attempting to debug TypeScript or JavaScript code on the server-side using Visual Studio Code with nodemon. I've set up a new configuration in la ...

The Nextjs application folder does not contain the getStaticPaths method

I encountered a problem with the latest nextjs app router when I tried to utilize SSG pages for my stapi blog, but kept receiving this error during the build process app/blog/[slug]/page.tsx Type error: Page "app/blog/[slug]/page.tsx" does not m ...

Guide on importing npm packages without TypeScript definitions while still enabling IDE to provide intelligent code completion features

I am currently utilizing an npm package that lacks type definitions for TypeScript. Specifically, I'm working with the react-google-maps library. Following their recommended approach, I have imported the following components from the package: import ...

Combining the power of Visual Studio Code with NodeJs allows for seamless detection of missing package namespaces

Recently, I've encountered a frustrating problem. It occurs when: I create a new Node project without any installed modules I use import '' and press ctrl+space between the brackets, resulting in unnecessary inferred namespaces. Alth ...

Find out if a dynamically imported component has finished loading in Nextjs

Here is a simplified version of my current situation import React, { useState } from 'react'; import dynamic from 'next/dynamic'; const DynamicImportedComponent = dynamic(() => import('Foo/baz'), { ssr: false, loading ...

Expanding the Warnings of React.Component

When I create a new class by extending React.Component in the following manner: export default class App extends React.Component<any, any > { constructor (props: React.ReactPropTypes) { super(props); } // other code } I encountere ...

Can SystemJS, JetBrains IntelliJ, and modules be combined effectively?

Looking for some clarification on the functionality of module includes and systemJS within an Angular2 app structure. I have set up a basic Angular2 app with the following layout: -app |-lib (contains shims and node libraries) |-components |-app |-app. ...

Having trouble with importing rxjs operators

After updating the imports for rxjs operators in my project to follow the new recommended syntax, I encountered an issue with the "do" operator. While switchMap and debounceTime were updated successfully like this: import { switchMap, debounceTime } ...

Improving the clarity of Jest snapshot test logs using styled from MUI

Currently, I am working with MUI v5 along with styled components and Jest snapshot testing. I am looking for a way to improve the logs generated when a snapshot test fails. Below is an example of the component I am dealing with: const styledProperties = n ...