无服务器框架将 Lambda 添加到现有 VPC 和子网

Posted

技术标签:

【中文标题】无服务器框架将 Lambda 添加到现有 VPC 和子网【英文标题】:Serverless Framework add Lambda to an Existing VPC and Subnet 【发布时间】:2018-11-03 01:09:30 【问题描述】:

是否可以创建无服务器框架 Lambda 部署,其中 Lambda 部署到现有 VPC 的 SecurityGroup 中?我不希望服务部署或其堆栈拥有网络工件?

【问题讨论】:

【参考方案1】:

是的。 serverless.yml 中的vpc 配置只需要引用现有的子网和安全组。像这样的:

vpc:
    securityGroupIds:
      - securityGroupId1
      - securityGroupId2
    subnetIds:
      - subnetId1
      - subnetId2

看看https://serverless.com/framework/docs/providers/aws/guide/functions/#vpc-configuration

【讨论】:

@Brian 这不起作用。由于某种原因,没有添加 VPC。 请注意,如果您已经部署了 serverless api,您可能需要使用sls deploy --force 甚至删除并重新部署您的 serverless api。 如果你想创建一个接口 vpc 端点以允许 lambda 连接到一个服务,你如何在通过 clouformation 创建 vpc 端点时给出 vpc Id ? 您可以使用 Outputs 在 CloudFormation 中导出 VPC id,然后使用 $cf:WhateverYourExportedVPCOutputNameIs 在 Serverless 中引用 VPC id【参考方案2】:

以下设置在无服务器版本 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

【讨论】:

【参考方案3】:

@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

【讨论】:

以上是关于无服务器框架将 Lambda 添加到现有 VPC 和子网的主要内容,如果未能解决你的问题,请参考以下文章

使用无服务器框架通过 VPC 设置 NAT 网关

将现有 Cognito UserPool 导入到无服务器框架堆栈

在无服务器框架中创建可用于 Lambda 函数的 RDS 实例

如何将无服务器 Step Function/状态机/Lambda 构建嵌套到现有 AWS CloudFormation ElasticBeanstalk 应用程序中?

在本地测试 Elasticache 和无服务器 AWS Lambda

如何将 VPC 和安全组分配给 AWS CDK 中的 Lambda?