无服务器框架:如何将 Lambda 添加到现有的 VPC 和子网中

25

是否可以创建一个无服务器框架Lambda部署,使Lambda部署到现有VPC的安全组中?我不想让服务部署或其堆栈拥有任何网络构件。


请转到 https://learnbatta.com/blog/serverless-add-aws-lambda-to-existing-vpc/ 了解如何将 AWS Lambda 添加到现有 VPC。 - anjaneyulubatta505
3个回答

34

@Brian 这个不行。出于某种原因,VPC没有被添加进去。 - node_saini
6
请注意,如果您已经部署了无服务器 API,您可能需要使用 sls deploy --force 命令,甚至需要删除并重新部署无服务器 API。 - Derrops
如果您想创建一个接口VPC端点以允许Lambda连接到服务,那么在通过CloudFormation创建VPC端点时,如何提供VPC ID? - iammrmehul
您可以使用CloudFormation中的Outputs导出VPC id,然后在Serverless中使用${cf:WhateverYourExportedVPCOutputNameIs}引用VPC id。 - Brian Winant

8
以下设置在 Serverless 版本 1.51.0 中对我完美地起作用。我包含了分段变量,因为我的环境使用不同的子网和安全组进行逻辑隔离。我的网络设置是一个已经存在的 VPC,具有子网和安全组。
provider:
  name: aws
  ....
  ....
  vpc:
    securityGroupIds:
      - ${self:custom.securityGroupId.${self:provider.stage}}
    subnetIds:
      - ${self:custom.subnetId.${self:provider.stage}}

custom:
  stages:
    - tst
    - dev
    - prd
  securityGroupId:
    local: sg-local
    tst: sg-tst
    dev: sg-dev
    prd: sg-prd
  subnetId:
    local: subnet-local
    tst: subnet-tst
    dev: subnet-dev
    prd: subnet-prd


plugins:
  - serverless-stage-manager

6

@Nebulastic提供的答案有所补充。

当您希望配置VPC Lambda以从多个子网执行不同阶段时,就可以使用此方法。

provider:
  name: aws
  vpc:
    securityGroupIds:
      - ${self:custom.securityGroupId.${self:provider.stage}}
    subnetIds:
      - ${self:custom.subnetId1.${self:provider.stage}}
      - ${self:custom.subnetId2.${self:provider.stage}}
      - ${self:custom.subnetId3.${self:provider.stage}}

custom:
  stage: ${opt:stage, self:provider.stage}

  securityGroupId:
    prod: sgId-prod
    test: sgId-test
    dev: sgId-dev
  subnetId1:
    prod: subnetId1-prod
    test: subnetId1-test
    dev: subnetId1-dev
  subnetId2:
    prod: subnetId2-prod
    test: subnetId2-test
    dev: subnetId2-dev
  subnetId2:
    prod: subnetId3-prod
    test: subnetId3-test
    dev: subnetId3-dev

你的解决方案依赖于每个阶段具有相同数量的元素。如果prod有三个子网,但dev只有两个,怎么办?是否有一种方法可以引用整个数组而不仅仅是单个元素? - Jacob Stamm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接